diff --git a/.env.example b/.env.example index 31a8c9a..4d410d5 100644 --- a/.env.example +++ b/.env.example @@ -71,13 +71,14 @@ PASSWORD_HASH_CONCURRENCY=1 APP_SUBNET=172.29.79.0/24 APP_FRONTEND_IP=172.29.79.10 # Registration and email confirmation. IDENTITY_KEY_SECRET is required. It -# keys idempotency records, rate-limit counters, and session CSRF tokens across -# restarts and instances. +# keys idempotency records, rate-limit counters, session CSRF tokens, and +# organization-scoped candidate aliases across restarts and instances. # Use at least 32 bytes. There is no usable example value: leave it empty here # and generate one for every deployment (Compose refuses an empty value): # openssl rand -base64 48 # A value that starts with replace-this is refused. Without it the backend refuses to start, unless a development stand sets -# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process). +# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process; candidate +# aliases also change after restart). IDENTITY_KEY_SECRET= # Registration and every verification resend count toward both per-address limits. VERIFICATION_MAIL_MIN_INTERVAL=1m diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index c662edc..557d71a 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -1488,10 +1488,7 @@ AssessmentItemNotCurrent: detail: The resource is in a state that does not allow this operation. trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f AssessmentFinalizeNotReady: - summary: Premature finalize; the problem does not list the unfinished parts - description: >- - Problem has no extension fields. The client reads what remains from the - attempt: `state`, `progress`, `current_item`, and `practices`. + summary: Premature finalize; the problem lists unanswered frozen items value: type: urn:lincodex:problem:state_conflict title: Resource state conflict @@ -1499,6 +1496,9 @@ AssessmentFinalizeNotReady: code: state_conflict detail: The resource is in a state that does not allow this operation. trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e + pending_item_ids: + - 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + - 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d AssessmentAttemptNotAvailable: summary: No attempt can start for the category now value: @@ -2484,7 +2484,7 @@ InvitationCreateFromNeed: summary: A draft for a candidate from the search results of a need description: "Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided." value: - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2625,7 +2625,7 @@ OrganizationInvitationDraft: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2688,7 +2688,7 @@ OrganizationInvitationDraftUpdated: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2752,7 +2752,7 @@ OrganizationInvitationDelivered: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2816,7 +2816,7 @@ OrganizationInvitationSalaryRaised: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2880,7 +2880,7 @@ OrganizationInvitationAccepted: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -2945,7 +2945,7 @@ OrganizationInvitationWithdrawn: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -3010,7 +3010,7 @@ OrganizationInvitationListPage: value: items: - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -3033,7 +3033,7 @@ OrganizationInvitationListPage: created_at: "2026-10-06T09:00:00Z" updated_at: "2026-10-06T15:00:00Z" - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 - candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb + candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB need: null state: declined expiry_reason: null @@ -4373,17 +4373,35 @@ PublishedCardPreview: - categories - stack card: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA categories: - specialization: backend grade: middle + strength: standard stack: - - PostgreSQL - - Kafka - experience_months: null - soft_skills: null - location: null - relocation: null + - postgresql + - kafka + self_assessment: null + experience_band: "1_3" + work_formats: null + salary_compatibility: null generated_at: "2026-10-06T09:30:00Z" +OrganizationAnonymousCandidateCard: + summary: An anonymous card currently visible to one organization + description: The alias is scoped to the reading organization; no contact values are included. + value: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + stack: + - postgresql + - kafka + self_assessment: null + experience_band: "1_3" + work_formats: null + salary_compatibility: null ClosedCardPreview: summary: The preview of a closed profile value: diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index d4550f1..52ea5bb 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -82,6 +82,19 @@ OrganizationId: type: string format: uuid example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 +CandidateHandle: + name: candidate_handle + in: path + required: true + description: >- + 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. + schema: + $ref: ./schemas.yml#/CandidateHandle + example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA NeedId: name: need_id in: path diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index a57b2ac..871e65a 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -316,15 +316,14 @@ AssessmentFinalizeConflict: The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. - The problem does not list the unfinished parts, because Problem allows - no extension fields; the attempt shows them in `state`, `progress`, - `current_item`, and `practices`. Or a request with the same - Idempotency-Key is still running, code idempotency_in_progress. Nothing - was changed in either case. + If required questions are unfinished, the response includes their frozen + IDs in `pending_item_ids`; other state conflicts omit that field. Or a + request with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was changed in either case. content: application/problem+json: schema: - $ref: ./schemas.yml#/Problem + $ref: ./schemas.yml#/AssessmentFinalizeConflictProblem examples: state_conflict: $ref: ./examples.yml#/AssessmentFinalizeNotReady diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index ebaa493..062ce31 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -25,12 +25,12 @@ PageInfo: description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. CandidateHandle: type: string - minLength: 1 - maxLength: 128 - pattern: ^[A-Za-z0-9_-]+$ - description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it. + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations. examples: - - cand_7Qm2xVb9Lr4Kp0Zt + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AssessmentMode: type: string description: 'Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. @@ -862,6 +862,7 @@ NumberAnswer: number: type: number format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber StringAnswer: type: object description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. @@ -1213,6 +1214,58 @@ AssessmentResult: root: '#/AssessmentQualifiedResult' corrective: '#/AssessmentCorrectiveResult' demo_express: '#/AssessmentExpressResult' +AssessmentFinalizeConflictProblem: + type: object + description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + errors: + type: array + maxItems: 100 + items: + $ref: '#/ProblemFieldError' + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items. AssessmentRealResultCommon: type: object description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. @@ -1594,6 +1647,120 @@ AssessmentAvailability: description: Questionnaire specializations in questionnaire order. items: $ref: '#/AssessmentSpecializationAvailability' +AssessmentSignalEvent: + description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention. + oneOf: + - $ref: '#/AssessmentFocusLossSignal' + - $ref: '#/AssessmentClipboardSignal' + - $ref: '#/AssessmentFullscreenExitSignal' + discriminator: + propertyName: kind + mapping: + focus_loss: '#/AssessmentFocusLossSignal' + copy: '#/AssessmentClipboardSignal' + paste: '#/AssessmentClipboardSignal' + cut: '#/AssessmentClipboardSignal' + fullscreen_exit: '#/AssessmentFullscreenExitSignal' +AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. +AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: Byte count only. Clipboard or selection contents are not transmitted or retained. +AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' +AssessmentSignalBatch: + type: object + description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/AssessmentSignalEvent' +AssessmentSignalReceipt: + type: object + description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.' + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: '#/Timestamp' ProfileVersion: type: integer format: int64 @@ -5413,17 +5580,19 @@ CardField: description: 'A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. - - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. + - categories: specialization and grade confirmed by an authoritative assessment result. - - stack: the technology tags of the profile. + - self_assessment: the candidate''s declared specialization and grade, separate from confirmed categories. - - experience: the total months of work experience, without employers, periods, or descriptions. + - stack: only recognized technology codes from the server''s closed taxonomy. - - soft_skills: the soft skills of the profile. + - experience: a coarse total-experience band, without employers, periods, or descriptions. - - location: the city or region of the profile. + - work_formats: explicitly selected work formats from the private questionnaire. - - relocation: whether the candidate is ready to relocate. + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. @@ -5432,15 +5601,18 @@ CardField: Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.' enum: - categories + - salary_compatibility + - self_assessment - stack - experience - soft_skills - location - relocation + - work_formats CardFieldSet: type: array minItems: 0 - maxItems: 6 + maxItems: 9 uniqueItems: true description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. items: @@ -5644,24 +5816,78 @@ CardCategory: required: - specialization - grade + - strength properties: specialization: $ref: '#/SpecializationCode' grade: $ref: '#/GradeCode' -AnonymousCardContent: + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. +CardSelfAssessment: type: object - description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are - defined by the search contract, which reuses this content. + description: Candidate-declared specialization and optional grade. This is never an assessment result. additionalProperties: false required: + - specialization + - confirmation_status + properties: + specialization: + $ref: '#/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' +CandidateExperienceBand: + type: string + description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned. + enum: + - '0_1' + - '1_3' + - '3_6' + - 6_plus + - '0_3' + - 3_plus +CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid +CandidateSalaryCompatibility: + type: string + description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible +AnonymousCardContent: + type: object + description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content. + additionalProperties: false + required: + - pseudonym - categories - stack - - experience_months - - soft_skills - - location - - relocation + - self_assessment + - experience_band + - work_formats + - salary_compatibility properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations. categories: type: - array @@ -5674,45 +5900,44 @@ AnonymousCardContent: type: - array - 'null' - maxItems: 30 - description: Technology tags of the candidate, or null. + maxItems: 4 + description: Recognized confirmed technology codes only, or null. items: - $ref: '#/StackTag' - experience_months: - type: - - integer - - 'null' - minimum: 0 - maximum: 1200 - description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null. - soft_skills: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: type: - array - 'null' - maxItems: 10 - description: Soft skills of the candidate, or null. + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. items: - type: string - minLength: 1 - maxLength: 50 - pattern: ^\S(?:.*\S)?$ - description: Plain text; clients show it as text, never as HTML. - location: + $ref: '#/CardSelfAssessment' + experience_band: + oneOf: + - $ref: '#/CandidateExperienceBand' + - type: 'null' + description: Coarse total work-experience bucket, or null. + work_formats: type: - - string + - array - 'null' - minLength: 1 - maxLength: 100 - pattern: ^\S(?:.*\S)?$ - description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML. - relocation: - type: - - boolean - - 'null' - description: Whether the candidate is ready to relocate, or null. + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: '#/CandidateWorkFormat' + salary_compatibility: + oneOf: + - $ref: '#/CandidateSalaryCompatibility' + - type: 'null' + description: Nullable compatibility result with no salary values. CardPreview: type: object - description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.' + description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. additionalProperties: false required: - state @@ -5813,7 +6038,7 @@ CardAccessKind: description: 'How an organization reached the candidate. - - card_viewed: an organization read the anonymous card in a search result. + - card_viewed: an organization read the permitted anonymous card. - contact_read: an organization read the contacts through the contact grant of an accepted invitation.' enum: @@ -5821,7 +6046,7 @@ CardAccessKind: - contact_read CardAccess: type: object - description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization. + description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization. additionalProperties: false required: - id @@ -6612,7 +6837,7 @@ SupportCase: - 'null' format: int32 minimum: 1 - description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.' + description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`. response_target: $ref: '#/SupportResponseTarget' decision: diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml index d1d13e1..f599cbd 100644 --- a/api/core/components/schemas/assessment_schemas.yml +++ b/api/core/components/schemas/assessment_schemas.yml @@ -947,6 +947,7 @@ schemas: number: type: number format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber StringAnswer: type: object description: >- @@ -1329,6 +1330,64 @@ schemas: root: "#/schemas/AssessmentQualifiedResult" corrective: "#/schemas/AssessmentCorrectiveResult" demo_express: "#/schemas/AssessmentExpressResult" + AssessmentFinalizeConflictProblem: + type: object + description: >- + A finalize state conflict. `pending_item_ids` is present only when the + attempt still has required questions without answers; it is omitted for + other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + errors: + type: array + maxItems: 100 + items: + $ref: "./problem_schemas.yml#/schemas/ProblemFieldError" + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: >- + Frozen item IDs still unanswered when finalize is rejected for an + incomplete attempt. Omitted when the conflict is unrelated to + unanswered items. AssessmentRealResultCommon: type: object description: >- diff --git a/api/core/components/schemas/assessment_signal_schemas.yml b/api/core/components/schemas/assessment_signal_schemas.yml new file mode 100644 index 0000000..561ff22 --- /dev/null +++ b/api/core/components/schemas/assessment_signal_schemas.yml @@ -0,0 +1,124 @@ +schemas: + AssessmentSignalEvent: + description: >- + One client-reported event bound to an item instance of the attempt. The + timestamp is untrusted input and is used only as event metadata; server + receipt time is authoritative for limits and retention. + oneOf: + - $ref: "#/schemas/AssessmentFocusLossSignal" + - $ref: "#/schemas/AssessmentClipboardSignal" + - $ref: "#/schemas/AssessmentFullscreenExitSignal" + discriminator: + propertyName: kind + mapping: + focus_loss: "#/schemas/AssessmentFocusLossSignal" + copy: "#/schemas/AssessmentClipboardSignal" + paste: "#/schemas/AssessmentClipboardSignal" + cut: "#/schemas/AssessmentClipboardSignal" + fullscreen_exit: "#/schemas/AssessmentFullscreenExitSignal" + AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. + AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: Byte count only. Clipboard or selection contents are not transmitted or retained. + AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + AssessmentSignalBatch: + type: object + description: >- + A bounded batch of client event metadata. The raw request body is limited + to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: "#/schemas/AssessmentSignalEvent" + AssessmentSignalReceipt: + type: object + description: >- + Receipt for the submitted batch. It contains no signal details, score, + review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: >- + `saturated` means no event from this batch was stored because the + attempt's bounded evidence storage is full. + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: "#/schemas/Timestamp" diff --git a/api/core/components/schemas/common_schemas.yml b/api/core/components/schemas/common_schemas.yml index 92c4821..1768181 100644 --- a/api/core/components/schemas/common_schemas.yml +++ b/api/core/components/schemas/common_schemas.yml @@ -34,16 +34,16 @@ schemas: must not parse, build, or store it beyond the current listing. CandidateHandle: type: string - minLength: 1 - maxLength: 128 - pattern: "^[A-Za-z0-9_-]+$" + minLength: 47 + maxLength: 47 + pattern: '^cv1_[A-Za-z0-9_-]{43}$' description: >- Opaque reference to a candidate as one organization sees it, taken - from a search result card of that organization. It is not the - candidate's account or profile identifier, it never contains an email - address or a phone number, and it means nothing to another - organization. The server resolves it only for the organization in the - path. Clients never parse it. It is shared by the invitations of - FR12 and the search results of FR11, which issue it. + from the organization-scoped anonymous card. It is a versioned HMAC + alias, not a candidate account or profile identifier; it contains no + contact information and is meaningless to another organization. The + server resolves it only against the current visible cohort of the + organization in the path. Clients never parse or construct it. It is + shared by the candidate-card read and invitations. examples: - - cand_7Qm2xVb9Lr4Kp0Zt + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA diff --git a/api/core/components/schemas/privacy_schemas.yml b/api/core/components/schemas/privacy_schemas.yml index c68922b..aaa4ede 100644 --- a/api/core/components/schemas/privacy_schemas.yml +++ b/api/core/components/schemas/privacy_schemas.yml @@ -28,27 +28,31 @@ schemas: description: |- A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. - - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. - - stack: the technology tags of the profile. - - experience: the total months of work experience, without employers, periods, or descriptions. - - soft_skills: the soft skills of the profile. - - location: the city or region of the profile. - - relocation: whether the candidate is ready to relocate. + - categories: specialization and grade confirmed by an authoritative assessment result. + - self_assessment: the candidate's declared specialization and grade, separate from confirmed categories. + - stack: only recognized technology codes from the server's closed taxonomy. + - experience: a coarse total-experience band, without employers, periods, or descriptions. + - work_formats: explicitly selected work formats from the private questionnaire. + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. enum: - categories + - salary_compatibility + - self_assessment - stack - experience - soft_skills - location - relocation + - work_formats CardFieldSet: type: array minItems: 0 - maxItems: 6 + maxItems: 9 uniqueItems: true description: >- Distinct card fields. The server stores them in ascending order of @@ -316,21 +320,70 @@ schemas: required: - specialization - grade + - strength properties: specialization: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" grade: $ref: "./catalog_schemas.yml#/schemas/GradeCode" + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. + CardSelfAssessment: + type: object + description: Candidate-declared specialization and optional grade. This is never an assessment result. + additionalProperties: false + required: + - specialization + - confirmation_status + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + CandidateExperienceBand: + type: string + description: >- + Coarse total experience bucket. Rare combinations may be generalized to + 0_3 or 3_plus before they are returned. + enum: + - "0_1" + - "1_3" + - "3_6" + - "6_plus" + - "0_3" + - "3_plus" + CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid + CandidateSalaryCompatibility: + type: string + description: >- + A coarse compatibility result only. No salary amount, minimum, range, + or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible AnonymousCardContent: type: object description: >- - The anonymous candidate card as an organization reads it. Only values - that the candidate confirmed reach it; an unconfirmed suggestion and an - unknown value never do. A free text value (a stack tag, a soft skill, the - location) that looks like a contact (an email address, a phone number, a - URL or domain, a Telegram link, an @handle) is dropped by the builder - and never published. It carries - no name, contact, resume text, employer, salary figure, account or + The anonymous candidate card as an organization reads it. Only explicitly + published values reach it; unconfirmed stack suggestions and unknown + values never do. Stack output uses a closed taxonomy. It carries no name, + contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted @@ -343,13 +396,22 @@ schemas: content. additionalProperties: false required: + - pseudonym - categories - stack - - experience_months - - soft_skills - - location - - relocation + - self_assessment + - experience_band + - work_formats + - salary_compatibility properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: '^cv1_[A-Za-z0-9_-]{43}$' + description: >- + Stable opaque alias scoped to the reading organization. It is not an + account or profile identifier and changes across organizations. categories: type: - array @@ -362,54 +424,51 @@ schemas: type: - array - "null" - maxItems: 30 - description: Technology tags of the candidate, or null. + maxItems: 4 + description: Recognized confirmed technology codes only, or null. items: - $ref: "./questionnaire_schemas.yml#/schemas/StackTag" - experience_months: - type: - - integer - - "null" - minimum: 0 - maximum: 1200 - description: >- - Total months of work experience, summed by the server without the - employers, periods, or descriptions, or null. - soft_skills: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: type: - array - "null" - maxItems: 10 - description: Soft skills of the candidate, or null. + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. items: - type: string - minLength: 1 - maxLength: 50 - pattern: '^\S(?:.*\S)?$' - description: Plain text; clients show it as text, never as HTML. - location: + $ref: "#/schemas/CardSelfAssessment" + experience_band: + oneOf: + - $ref: "#/schemas/CandidateExperienceBand" + - type: "null" + description: Coarse total work-experience bucket, or null. + work_formats: type: - - string + - array - "null" - minLength: 1 - maxLength: 100 - pattern: '^\S(?:.*\S)?$' - description: >- - City or region as free text, never a street address, or null. - Plain text; clients show it as text, never as HTML. - relocation: - type: - - boolean - - "null" - description: Whether the candidate is ready to relocate, or null. + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: "#/schemas/CandidateWorkFormat" + salary_compatibility: + oneOf: + - $ref: "#/schemas/CandidateSalaryCompatibility" + - type: "null" + description: Nullable compatibility result with no salary values. CardPreview: type: object description: >- - What an organization that the candidate does not hide the profile from - would read now, computed from the current profile, the current - publication, and the consent ledger. It is a read for the candidate: it - creates no view and no history record, and it never reaches an - organization. `card` is null while the profile is closed. + A private candidate preview computed from the current profile, + publication, and consent ledger. Its pseudonym uses a separate preview + context and is not an organization's alias. Organization-specific + visibility filters and cohort checks can further generalize or suppress + the organization-facing card. This read creates no view or history + record and never reaches an organization. `card` is null while the + profile is closed. additionalProperties: false required: - state @@ -520,7 +579,7 @@ schemas: description: |- How an organization reached the candidate. - - card_viewed: an organization read the anonymous card in a search result. + - card_viewed: an organization read the permitted anonymous card. - contact_read: an organization read the contacts through the contact grant of an accepted invitation. enum: - card_viewed @@ -529,12 +588,12 @@ schemas: type: object description: >- One access of an organization to the card or the contacts of the - current candidate. `organization` is null for a view by an - organization that has no invitation relation with the candidate, so the - history shows that the card was viewed without naming a company that - the candidate cannot otherwise see; whether the candidate should learn - the name is an open product question. The record carries no query, - ranking, or search filter of the organization. + current candidate. A retained access permits the candidate to see the + organization's identifier and current name and to hide their profile + from it. `organization` is null when the organization cannot be + presented. Earlier permitted accesses remain after hiding. The record + carries no employee identity, query, ranking, or search filter of the + organization. additionalProperties: false required: - id diff --git a/api/core/components/schemas/support_schemas.yml b/api/core/components/schemas/support_schemas.yml index 5917216..c4c1e8d 100644 --- a/api/core/components/schemas/support_schemas.yml +++ b/api/core/components/schemas/support_schemas.yml @@ -533,12 +533,12 @@ schemas: format: int32 minimum: 1 description: >- - For a manual assessment, the version of the published rubric of the - category that the server fixed on creation; the expert assesses with - it, the same rubric as the automated assessment. Null for other - types, and null for a manual assessment whose category has no - published rubric yet: the case then waits in `waiting_expert` and - the client says so instead of promising a date. + For a manual assessment, the version of the grading policy pinned + by the server at creation. The exact reviewed category opening and + rubric manifest are retained privately so the expert can use the + same rubric as automated assessment. Null for other types and for a + manual assessment without one unique current reviewed category; the + case still waits in `waiting_expert`. response_target: $ref: "#/schemas/SupportResponseTarget" decision: diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 906d627..59d2b8a 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -854,6 +854,58 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/signals: + post: + operationId: RecordMyAssessmentAttemptSignals + summary: Store a bounded batch of client-reported assessment signals. + description: |- + 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. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalBatch' + responses: + '200': + description: The stored or replayed receipt. A saturated receipt explicitly says that none of this batch's events was stored. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/me/assessment-attempts/{attempt_id}/answers: post: operationId: SubmitMyAssessmentAnswer @@ -954,7 +1006,7 @@ paths: A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this 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. + 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. 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), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. security: @@ -1470,6 +1522,52 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}: + get: + operationId: GetOrganizationCandidateCard + summary: Read one currently visible anonymous candidate card. + description: |- + 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. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/CandidateHandle' + responses: + '200': + description: The current anonymous card for this organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AnonymousCardContent' + examples: + published: + $ref: '#/components/examples/OrganizationAnonymousCandidateCard' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/organizations/{org_id}/invitations: get: operationId: ListOrganizationInvitations @@ -2529,9 +2627,11 @@ paths: operationId: GetMyCardPreview summary: Preview the anonymous card that organizations would read. description: |- - 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. security: @@ -2659,7 +2759,7 @@ paths: The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. - 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. + 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 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 other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. @@ -2775,9 +2875,9 @@ paths: description: |- Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. - 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. + 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 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. security: @@ -5026,6 +5126,7 @@ components: number: type: number format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber StringAnswer: type: object description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. @@ -5146,6 +5247,120 @@ components: $ref: '#/components/schemas/AssessmentItemId' answer: $ref: '#/components/schemas/AssessmentAnswer' + AssessmentSignalEvent: + description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention. + oneOf: + - $ref: '#/components/schemas/AssessmentFocusLossSignal' + - $ref: '#/components/schemas/AssessmentClipboardSignal' + - $ref: '#/components/schemas/AssessmentFullscreenExitSignal' + discriminator: + propertyName: kind + mapping: + focus_loss: '#/components/schemas/AssessmentFocusLossSignal' + copy: '#/components/schemas/AssessmentClipboardSignal' + paste: '#/components/schemas/AssessmentClipboardSignal' + cut: '#/components/schemas/AssessmentClipboardSignal' + fullscreen_exit: '#/components/schemas/AssessmentFullscreenExitSignal' + AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. + AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: Byte count only. Clipboard or selection contents are not transmitted or retained. + AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + AssessmentSignalBatch: + type: object + description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/components/schemas/AssessmentSignalEvent' + AssessmentSignalReceipt: + type: object + description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.' + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: '#/components/schemas/Timestamp' AssessmentFinalization: type: object description: Command to finalize the attempt. @@ -6817,7 +7032,7 @@ components: - 'null' format: int32 minimum: 1 - description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.' + description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`. response_target: $ref: '#/components/schemas/SupportResponseTarget' decision: @@ -6967,12 +7182,12 @@ components: - 7 CandidateHandle: type: string - minLength: 1 - maxLength: 128 - pattern: ^[A-Za-z0-9_-]+$ - description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it. + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations. examples: - - cand_7Qm2xVb9Lr4Kp0Zt + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA InvitationRoleTitle: type: string minLength: 1 @@ -8495,27 +8710,31 @@ components: description: |- A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. - - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. - - stack: the technology tags of the profile. - - experience: the total months of work experience, without employers, periods, or descriptions. - - soft_skills: the soft skills of the profile. - - location: the city or region of the profile. - - relocation: whether the candidate is ready to relocate. + - categories: specialization and grade confirmed by an authoritative assessment result. + - self_assessment: the candidate's declared specialization and grade, separate from confirmed categories. + - stack: only recognized technology codes from the server's closed taxonomy. + - experience: a coarse total-experience band, without employers, periods, or descriptions. + - work_formats: explicitly selected work formats from the private questionnaire. + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. enum: - categories + - salary_compatibility + - self_assessment - stack - experience - soft_skills - location - relocation + - work_formats CardFieldSet: type: array minItems: 0 - maxItems: 6 + maxItems: 9 uniqueItems: true description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. items: @@ -8715,23 +8934,37 @@ components: required: - specialization - grade + - strength properties: specialization: $ref: '#/components/schemas/SpecializationCode' grade: $ref: '#/components/schemas/GradeCode' + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. AnonymousCardContent: type: object - description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content. + description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content. additionalProperties: false required: + - pseudonym - categories - stack - - experience_months - - soft_skills - - location - - relocation + - self_assessment + - experience_band + - work_formats + - salary_compatibility properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations. categories: type: - array @@ -8744,45 +8977,44 @@ components: type: - array - 'null' - maxItems: 30 - description: Technology tags of the candidate, or null. + maxItems: 4 + description: Recognized confirmed technology codes only, or null. items: - $ref: '#/components/schemas/StackTag' - experience_months: - type: - - integer - - 'null' - minimum: 0 - maximum: 1200 - description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null. - soft_skills: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: type: - array - 'null' - maxItems: 10 - description: Soft skills of the candidate, or null. + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. items: - type: string - minLength: 1 - maxLength: 50 - pattern: ^\S(?:.*\S)?$ - description: Plain text; clients show it as text, never as HTML. - location: + $ref: '#/components/schemas/CardSelfAssessment' + experience_band: + oneOf: + - $ref: '#/components/schemas/CandidateExperienceBand' + - type: 'null' + description: Coarse total work-experience bucket, or null. + work_formats: type: - - string + - array - 'null' - minLength: 1 - maxLength: 100 - pattern: ^\S(?:.*\S)?$ - description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML. - relocation: - type: - - boolean - - 'null' - description: Whether the candidate is ready to relocate, or null. + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: '#/components/schemas/CandidateWorkFormat' + salary_compatibility: + oneOf: + - $ref: '#/components/schemas/CandidateSalaryCompatibility' + - type: 'null' + description: Nullable compatibility result with no salary values. CardPreview: type: object - description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.' + description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. additionalProperties: false required: - state @@ -8877,14 +9109,14 @@ components: description: |- How an organization reached the candidate. - - card_viewed: an organization read the anonymous card in a search result. + - card_viewed: an organization read the permitted anonymous card. - contact_read: an organization read the contacts through the contact grant of an accepted invitation. enum: - card_viewed - contact_read CardAccess: type: object - description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization. + description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization. additionalProperties: false required: - id @@ -9194,6 +9426,58 @@ components: - task_language - root_attempt_id - chain_deadline + AssessmentFinalizeConflictProblem: + type: object + description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + errors: + type: array + maxItems: 100 + items: + $ref: '#/components/schemas/ProblemFieldError' + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items. AssessmentRealResultCommon: type: object description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. @@ -9460,6 +9744,47 @@ components: description: Short educational feedback about this training run. decided_at: $ref: '#/components/schemas/Timestamp' + CardSelfAssessment: + type: object + description: Candidate-declared specialization and optional grade. This is never an assessment result. + additionalProperties: false + required: + - specialization + - confirmation_status + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + CandidateExperienceBand: + type: string + description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned. + enum: + - '0_1' + - '1_3' + - '3_6' + - 6_plus + - '0_3' + - 3_plus + CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid + CandidateSalaryCompatibility: + type: string + description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible parameters: IdempotencyKey: name: Idempotency-Key @@ -9577,6 +9902,14 @@ components: type: string format: uuid example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + CandidateHandle: + name: candidate_handle + in: path + required: true + description: 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. + schema: + $ref: '#/components/schemas/CandidateHandle' + example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA headers: ETag: description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. @@ -9886,11 +10219,11 @@ components: idempotency_in_progress: $ref: '#/components/examples/IdempotencyInProgress' AssessmentFinalizeConflict: - description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. The problem does not list the unfinished parts, because Problem allows no extension fields; the attempt shows them in `state`, `progress`, `current_item`, and `practices`. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.' + description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. If required questions are unfinished, the response includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.' content: application/problem+json: schema: - $ref: '#/components/schemas/Problem' + $ref: '#/components/schemas/AssessmentFinalizeConflictProblem' examples: state_conflict: $ref: '#/components/examples/AssessmentFinalizeNotReady' @@ -11411,6 +11744,24 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c + StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b + PayloadTooLarge: + summary: The request body exceeds the limit + value: + type: urn:lincodex:problem:payload_too_large + title: Request body too large + status: 413 + code: payload_too_large + detail: Reduce the request body size and retry. + trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e AssessmentChoiceAnswer: summary: Answer item 1 of version 1 value: @@ -11562,8 +11913,7 @@ components: value: expected_version: 20 AssessmentFinalizeNotReady: - summary: Premature finalize; the problem does not list the unfinished parts - description: 'Problem has no extension fields. The client reads what remains from the attempt: `state`, `progress`, `current_item`, and `practices`.' + summary: Premature finalize; the problem lists unanswered frozen items value: type: urn:lincodex:problem:state_conflict title: Resource state conflict @@ -11571,6 +11921,9 @@ components: code: state_conflict detail: The resource is in a state that does not allow this operation. trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e + pending_item_ids: + - 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + - 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d AssessmentDemoBasicResult: summary: demo_basic result with a confirmed grade and no uncertainty description: demo_basic computes no ability estimate, so `uncertainty` and `strength` are null rather than zero, and no percentile is shown. The pass mark comes from basic grading policy version 1, and the limitations name the uncalibrated thresholds, the demo bank, and the missing practice. A first confirmation is not a promotion, so the higher grade can be tested at once. The result never changes; a repeated finalize returns the completed attempt, and this read returns the same result. @@ -12738,13 +13091,29 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d + OrganizationAnonymousCandidateCard: + summary: An anonymous card currently visible to one organization + description: The alias is scoped to the reading organization; no contact values are included. + value: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + stack: + - postgresql + - kafka + self_assessment: null + experience_band: '1_3' + work_formats: null + salary_compatibility: null OrganizationInvitationListPage: summary: The last page of the invitations of an organization description: The organization sees that the second invitation was declined, but not the reason or the comment. value: items: - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -12767,7 +13136,7 @@ components: created_at: '2026-10-06T09:00:00Z' updated_at: '2026-10-06T15:00:00Z' - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 - candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb + candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB need: null state: declined expiry_reason: null @@ -12793,7 +13162,7 @@ components: summary: A draft for a candidate from the search results of a need description: 'Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided.' value: - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -12841,7 +13210,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -13007,7 +13376,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -13071,7 +13440,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -13179,7 +13548,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -13238,15 +13607,6 @@ components: delivered_at: null viewed_at: null responded_at: null - StateConflict: - summary: The resource state does not allow the operation - value: - type: urn:lincodex:problem:state_conflict - title: Resource state conflict - status: 409 - code: state_conflict - detail: The resource is in a state that does not allow this operation. - trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b InvitationStaleTerms: summary: The acceptance named a terms version that is no longer current description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision. @@ -13309,7 +13669,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -13377,7 +13737,7 @@ components: value: id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 - candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA need: need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 requirements_version: 3 @@ -14146,16 +14506,18 @@ components: - categories - stack card: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA categories: - specialization: backend grade: middle + strength: standard stack: - - PostgreSQL - - Kafka - experience_months: null - soft_skills: null - location: null - relocation: null + - postgresql + - kafka + self_assessment: null + experience_band: '1_3' + work_formats: null + salary_compatibility: null generated_at: '2026-10-06T09:30:00Z' ClosedCardPreview: summary: The preview of a closed profile @@ -14539,15 +14901,6 @@ components: message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. created_at: '2026-10-01T10:00:00Z' updated_at: '2026-10-09T14:30:00Z' - PayloadTooLarge: - summary: The request body exceeds the limit - value: - type: urn:lincodex:problem:payload_too_large - title: Request body too large - status: 413 - code: payload_too_large - detail: Reduce the request body size and retry. - trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e PreconditionRequired: summary: The operation requires If-Match value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 684fb5f..6ce1d3b 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -109,6 +109,8 @@ paths: $ref: ./routes/candidate_assessment_attempt.yml /api/v1/me/assessment-attempts/{attempt_id}/sessions: $ref: ./routes/candidate_assessment_attempt_sessions.yml + /api/v1/me/assessment-attempts/{attempt_id}/signals: + $ref: ./routes/candidate_assessment_signals.yml /api/v1/me/assessment-attempts/{attempt_id}/answers: $ref: ./routes/candidate_assessment_attempt_answers.yml /api/v1/me/assessment-attempts/{attempt_id}/finalize: @@ -125,6 +127,8 @@ paths: $ref: ./routes/organization_needs.yml /api/v1/organizations/{org_id}/needs/{need_id}: $ref: ./routes/organization_need.yml + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}: + $ref: ./routes/organization_candidate_card.yml /api/v1/organizations/{org_id}/invitations: $ref: ./routes/organization_invitations.yml /api/v1/organizations/{org_id}/invitations/{invitation_id}: @@ -439,6 +443,18 @@ components: $ref: ./components/schemas.yml#/AssessmentAnswer AssessmentAnswerSubmission: $ref: ./components/schemas.yml#/AssessmentAnswerSubmission + AssessmentSignalEvent: + $ref: ./components/schemas.yml#/AssessmentSignalEvent + AssessmentFocusLossSignal: + $ref: ./components/schemas.yml#/AssessmentFocusLossSignal + AssessmentClipboardSignal: + $ref: ./components/schemas.yml#/AssessmentClipboardSignal + AssessmentFullscreenExitSignal: + $ref: ./components/schemas.yml#/AssessmentFullscreenExitSignal + AssessmentSignalBatch: + $ref: ./components/schemas.yml#/AssessmentSignalBatch + AssessmentSignalReceipt: + $ref: ./components/schemas.yml#/AssessmentSignalReceipt AssessmentFinalization: $ref: ./components/schemas.yml#/AssessmentFinalization AssessmentOutcome: diff --git a/api/core/routes/candidate_assessment_attempt_finalize.yml b/api/core/routes/candidate_assessment_attempt_finalize.yml index 6d8eb51..7df844a 100644 --- a/api/core/routes/candidate_assessment_attempt_finalize.yml +++ b/api/core/routes/candidate_assessment_attempt_finalize.yml @@ -13,7 +13,7 @@ post: A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this 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. + 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. 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), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. security: diff --git a/api/core/routes/candidate_assessment_signals.yml b/api/core/routes/candidate_assessment_signals.yml new file mode 100644 index 0000000..3b08129 --- /dev/null +++ b/api/core/routes/candidate_assessment_signals.yml @@ -0,0 +1,53 @@ +post: + operationId: RecordMyAssessmentAttemptSignals + summary: Store a bounded batch of client-reported assessment signals. + description: |- + 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. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalBatch + responses: + "200": + description: >- + The stored or replayed receipt. A saturated receipt explicitly says + that none of this batch's events was stored. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + "413": + $ref: ../components/responses.yml#/PayloadTooLarge + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_access_history.yml b/api/core/routes/candidate_privacy_access_history.yml index 878be37..064e2e9 100644 --- a/api/core/routes/candidate_privacy_access_history.yml +++ b/api/core/routes/candidate_privacy_access_history.yml @@ -4,9 +4,9 @@ get: description: |- Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. - 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. + 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 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. security: diff --git a/api/core/routes/candidate_privacy_hidden_organization.yml b/api/core/routes/candidate_privacy_hidden_organization.yml index 463915e..8746e53 100644 --- a/api/core/routes/candidate_privacy_hidden_organization.yml +++ b/api/core/routes/candidate_privacy_hidden_organization.yml @@ -6,7 +6,7 @@ put: The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. - 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. + 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 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 other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. diff --git a/api/core/routes/candidate_privacy_preview.yml b/api/core/routes/candidate_privacy_preview.yml index 4c5e6a9..ae5be3e 100644 --- a/api/core/routes/candidate_privacy_preview.yml +++ b/api/core/routes/candidate_privacy_preview.yml @@ -2,9 +2,11 @@ get: operationId: GetMyCardPreview summary: Preview the anonymous card that organizations would read. description: |- - 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. security: diff --git a/api/core/routes/organization_candidate_card.yml b/api/core/routes/organization_candidate_card.yml new file mode 100644 index 0000000..84bed40 --- /dev/null +++ b/api/core/routes/organization_candidate_card.yml @@ -0,0 +1,45 @@ +get: + operationId: GetOrganizationCandidateCard + summary: Read one currently visible anonymous candidate card. + description: |- + 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. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/CandidateHandle + responses: + "200": + description: The current anonymous card for this organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AnonymousCardContent + examples: + published: + $ref: ../components/examples.yml#/OrganizationAnonymousCandidateCard + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/README.en.md b/backend/README.en.md index 2998fb7..99fb54e 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -26,7 +26,7 @@ HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int` Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF. -Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account or profile use. A separate manual-assessment request is planned, but its endpoint is not implemented. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously. +Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously. `make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request. @@ -34,20 +34,38 @@ Revoking C2 makes the publication effectively closed and hides its fields throug `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved. -The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Needs and invitations remain unimplemented, but their routes already enforce the common owner check before the 501 fallback. +The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes still enforce the common owner check before the 501 fallback; their business operations remain unimplemented. `TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL. `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request. -## Need storage +## Organization needs -Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict. Need business endpoints remain unimplemented at this storage stage. +Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict. + +The owner-scoped create, read, list, and update operations live in `internal/adapter/primary/http/v1/need.go`. Every operation checks the current verified employer account and locks its active owner membership in the transaction. List cursors carry both account and organization scope. Creates retain the original public response for the 24-hour idempotency window, even after a later edit. + +Source text is parsed locally by deterministic rules into unconfirmed suggestions. Unknown or ambiguous values remain unknown. Confirming a stored suggestion preserves its origin; a manual replacement records a manual origin. Editing source text preserves confirmed values, and removing a suggestion prevents later extraction from silently restoring it. Readiness is derived from confirmed requirements. Category recommendations currently report `not_available` without confirmed skills and `pending` otherwise; the category recommendation calculator is not implemented yet. `requirements_version` identifies the snapshot where confirmed requirements last changed. Editing only the title, source text, or unconfirmed suggestions leaves that reference unchanged. Domain no-ops preserve both versions. Snapshots preserve provenance, reject oversized content, and use UTC microsecond timestamps. Current and historical reads require the organization ID; immutable history rejects ordinary UPDATE and DELETE. Down migration removes both tables and their history, so it is destructive after data has been written. `TestOrganizationNeedsStorage` exercises actual PostgreSQL isolation, history, concurrent updates, transaction rollback, immutable snapshots, and storage bounds. The caller must perform the existing active-owner check in the same business operation; storage scope alone does not grant company access. +Migration `00026_create_organization_need_creation_results.sql` adds create-response storage and 8 KiB of database representation headroom for JSONB whitespace. The compact domain snapshot limit remains 256 KiB. Its down migration refuses to discard live replay results or restore the previous database bound over larger stored snapshots. Check those conditions before rollback; it does not remove need history to make a downgrade succeed. + +## Support cases + +Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent. + +A manual request pins the current published rubric for its specialization and grade. The API shows the grading-policy version; private references retain the exact category opening and immutable family-version manifest. Later publications do not change an existing case's rubric. Without one unambiguous current rubric, the version remains `null` and the case waits for an expert. + +Creation requires an explicit support section in the effective product policy. `DemoProductPolicyV2` includes it; normal startup still seeds only the immutable V1 policy. The demo targets are five business days for support, complaints, and manual assessment, and ten for appeals. The versioned calendar counts UTC weekdays without public holidays and does not pause while waiting for the user. These are operational targets, not legal deadlines. + +The account-wide rolling request limit is checked under a database lock before idempotent replay. Valid retries consume that request budget and return the original creation response during the 24-hour window. A 429 response includes `Retry-After`. GET and list show the current status, public history, and current overdue flag. Migration `00025_create_support_cases.sql` stores immutable events and replay results; rollback removes these records and is destructive. + +`TestSupportCasesOverHTTP` covers real sessions, owner isolation, typed-reference checks, replay, manual assessment without C3, and request limits. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` checks concurrent requests and clock ordering. Expert processing and references to not-yet-implemented invitations or anti-cheat reviews remain unavailable. + ## Candidate questionnaire Verified candidates can read and replace their own questionnaire through `GET/PUT /api/v1/me/questionnaire`. The questionnaire has a separate version and stores self-assessment, work formats, optional experience totals, and one or two specializations. It cannot assign confirmed grades. An identical retry returns the saved record without advancing its version; a stale changed body returns 412, as specified by the API contract. Concurrent identical writes also return the same winning record. @@ -58,4 +76,30 @@ The public specialization catalog derives readiness from the current published b `TestCandidateQuestionnaireOverHTTP` covers persistence, account isolation, version races, rollback, conditional onboarding, and changing bank availability. Company quota storage and its calling contract are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md). +## Assessment attempts + +A candidate creates an attempt through `POST /api/v1/me/assessment-attempts`, reads it by ID, and resumes work through `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Real assessment requires current C3 consent; the owner's attempt history remains readable after revocation. GET neither consumes sessions nor changes state. A command with a stale version returns 412. + +Creation pins the policy, bank and algorithm versions, the published family manifest, and generated question instances. The API response excludes answer keys, seeds, and private rubrics. Root-attempt quota is candidate-wide; retry and promotion intervals apply per specialization. A corrective attempt retains its root and the original chain deadline. Training `demo_express` uses a separate explicitly published bank and consumes no real-assessment quota. + +Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records. + +Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. Category assignment remains separate work; a basic threshold is not evidence of calibration. + +## Assessment signals + +The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt. + +The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Browser collection and interpretation of these signals are separate work. + +## Anonymous profile projection + +The organization-scoped projection uses purpose-separated HMAC aliases, a closed skill taxonomy, coarse experience bands, and explicitly selected publication fields. Confirmed categories and self-assessed grades remain separate. It excludes contacts, employer names, free text, exact salary, and account identifiers. Overlapping work periods count once. + +The repository filters current C2 publication and hidden organizations before building the cohort. Complete visible feature combinations with fewer than five candidates are generalized or suppressed. This reduces identification risk; it does not guarantee anonymity. The private owner-preview alias uses a separate purpose. Category and salary compatibility inputs remain absent until their authoritative source supplies them; missing evidence is never inferred from a claimed grade. + +Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me/privacy/preview`, change history at `GET /api/v1/me/privacy/history`, and card views at `GET /api/v1/me/privacy/access-history`. Hidden organizations are listed at `GET /api/v1/me/privacy/hidden-organizations` and changed through `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Publication and search status use `PUT /api/v1/me/privacy/publication` and `PUT /api/v1/me/privacy/search-status`. The data is scoped to the candidate in the current session, responses use `Cache-Control: no-store`, and writes require the session CSRF token and an exact allowed Origin. C2, publication, search status, and hidden organizations are independent: changing one does not enable another. Search status is a statement by the candidate, not consent. + +An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details. + See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md). diff --git a/backend/README.md b/backend/README.md index 4cc8aea..5f5ba78 100644 --- a/backend/README.md +++ b/backend/README.md @@ -26,7 +26,7 @@ Публично доступен только текущий текст C1 для регистрации. Подтвержденный пользователь может прочитать текущие тексты C1/C2/C3/C5 перед выдачей в настройках и постранично получить только собственный журнал согласий. C1 можно выдать аккаунту любого сценария; C2, C3 и C5 доступны кандидату. Изменения требуют явного подтверждения, exact Origin и session-bound CSRF. -Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт или профиль. Отдельный запрос ручной оценки запланирован, но его endpoint пока не реализован. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно. +Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт, профиль или запрос ручной оценки через поддержку. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно. Проверку полного HTTP-пути с PostgreSQL и Redis запускает `make -C backend test-int`; тест `TestConsentSettingsOverHTTP` покрывает тексты, журнал, grants, revocation effects и C1 deletion request. @@ -34,20 +34,38 @@ Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется. -Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Потребности и приглашения пока не реализованы, но их пути уже защищены общей проверкой владельца до ответа 501. +Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца до ответа 501; их бизнес-операции пока не реализованы. `TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа. `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе. -## Хранилище потребностей +## Потребности организаций -Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412. На этом этапе хранилища бизнес-операции HTTP потребностей еще не реализованы. +Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412. + +Операции создания, чтения, списка и изменения доступны владельцу и находятся в `internal/adapter/primary/http/v1/need.go`. Каждая операция проверяет текущую подтвержденную учетную запись работодателя и блокирует активное членство владельца в транзакции. Курсор списка содержит область учетной записи и организации. Создание сохраняет исходный публичный ответ на 24 часа для повторов с тем же ключом, даже после последующего изменения. + +Исходный текст разбирается локально детерминированными правилами в неподтвержденные предложения. Неизвестные и неоднозначные значения остаются неизвестными. Подтверждение сохраненного предложения сохраняет его происхождение; ручная замена получает ручное происхождение. Изменение исходного текста сохраняет подтвержденные значения, а удаление предложения запрещает разбору незаметно восстановить его позднее. Готовность вычисляется по подтвержденным требованиям. Рекомендации категорий пока возвращают `not_available` без подтвержденных навыков и `pending` в остальных случаях; вычисление рекомендаций категорий еще не реализовано. `requirements_version` указывает на снимок последнего изменения подтвержденных требований. Правка только названия, исходного текста или неподтвержденных предложений сохраняет эту ссылку. Доменный no-op сохраняет обе версии. Снимки сохраняют происхождение полей, отклоняют слишком большой объем данных и используют время UTC с точностью до микросекунд. Чтение текущей и исторической версии требует ID организации; обычные UPDATE и DELETE истории запрещены. Откат миграции удаляет обе таблицы вместе с историей, поэтому после записи данных он приводит к их потере. `TestOrganizationNeedsStorage` проверяет на настоящем PostgreSQL изоляцию, историю, конкурентные обновления, откат транзакции, неизменяемость снимков и ограничения объема. Вызывающая бизнес-операция должна применять существующую проверку активного владельца; область организации в хранилище сама по себе не дает доступа к компании. +Миграция `00026_create_organization_need_creation_results.sql` добавляет хранение ответа создания и запас 8 KiB для пробелов в представлении JSONB. Ограничение компактного доменного снимка остается 256 KiB. Обратная миграция отказывается удалять действующие результаты повторов или восстанавливать прежний предел БД поверх более крупных сохраненных снимков. Перед откатом нужно проверить эти условия; история потребностей не удаляется ради успешного отката. + +## Обращения в поддержку + +Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие. + +Ручной запрос фиксирует текущую опубликованную рубрику для выбранных специализации и грейда. API показывает версию политики оценивания; внутренние ссылки сохраняют точное открытие категории и неизменяемый набор версий семейств. Последующие публикации не меняют рубрику существующего обращения. При отсутствии однозначной актуальной рубрики версия остается `null`, а обращение ожидает эксперта. + +Для создания нужен явный раздел поддержки в действующей продуктовой политике. Он есть в `DemoProductPolicyV2`; обычный запуск по-прежнему создает только неизменяемую политику V1. Демо-срок составляет пять рабочих дней для поддержки, жалоб и ручной оценки и десять для апелляций. Версионированный календарь считает будни UTC без государственных праздников и не приостанавливает срок при ожидании пользователя. Это операционные ориентиры, а не юридические сроки. + +Скользящий лимит запросов аккаунта проверяется под блокировкой БД до идемпотентного повтора. Корректные повторы расходуют этот бюджет и возвращают исходный ответ создания в течение 24 часов. Ответ 429 содержит `Retry-After`. GET и список показывают актуальный статус, публичную историю и текущий признак просрочки. Миграция `00025_create_support_cases.sql` хранит неизменяемые события и результаты повторов; откат удаляет эти записи и является разрушительным. + +`TestSupportCasesOverHTTP` проверяет настоящие сессии, изоляцию владельцев, типизированные ссылки, повторы, ручную оценку без C3 и лимиты запросов. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` проверяет конкурентные запросы и порядок времени. Обработка экспертом и ссылки на еще не реализованные приглашения или античит-проверки остаются недоступны. + ## Анкета кандидата Подтвержденный кандидат читает и заменяет собственную анкету через `GET/PUT /api/v1/me/questionnaire`. Анкета имеет отдельную версию и хранит самооценку, форматы работы, необязательные суммы опыта и одну или две специализации. Она не назначает подтвержденные грейды. Идентичный повтор возвращает сохраненную запись без повышения версии; измененное тело с устаревшей версией получает 412 согласно контракту API. Одновременные одинаковые записи также возвращают одну победившую запись. @@ -58,4 +76,30 @@ `TestCandidateQuestionnaireOverHTTP` проверяет сохранность, изоляцию аккаунтов, конкурентные версии, откат, условный переход шага и изменение доступности банка. Хранилище квот компании и порядок его вызова описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md). +## Попытки оценки + +Кандидат создает попытку через `POST /api/v1/me/assessment-attempts`, читает ее по ID и возобновляет работу командой `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Реальная оценка требует действующего C3; история собственной попытки остается доступной после его отзыва. GET не расходует сессии и не меняет состояние. Команда с устаревшей версией возвращает 412. + +Создание фиксирует версии политики, банка и алгоритма, опубликованный набор семейств и сгенерированные экземпляры вопросов. Ответ API не содержит ключей ответов, seed или приватных рубрик. Квота корневых попыток общая для кандидата, а ограничения повторов и повышения грейда действуют по специализации. Корректирующая попытка сохраняет корень и исходный срок цепочки. Учебный `demo_express` использует отдельный явно опубликованный банк и не расходует квоту реальной оценки. + +Повтор команды с тем же ключом и телом возвращает сохраненный ответ в течение 24 часов. Повтор ключа с другим телом возвращает 422; недоступный банк или исчерпанная квота - 409 `state_conflict`. PostgreSQL сериализует проверку квоты и изменения сессии, а доменное время берется после ожидания блокировок. Миграция 24 добавляет попытки, экземпляры вопросов, учебные привязки и сохраненные ответы команд; ее откат удаляет эти данные. + +Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Присвоение категории остается отдельной работой; базовый порог не подтверждает калибровку. + +## Сигналы прохождения оценки + +Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки. + +Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Сбор событий браузером и их интерпретация относятся к отдельной работе. + +## Анонимная проекция профиля + +Проекция для организации использует HMAC-псевдонимы с разделением назначений ключей, закрытый справочник навыков, диапазоны стажа и явно выбранные поля публикации. Подтвержденные категории и самооценка разделены. Контакты, работодатели, свободный текст, точная зарплата и идентификаторы аккаунта исключены. Пересекающиеся периоды работы учитываются один раз. + +Репозиторий проверяет актуальную публикацию по C2 и скрытые организации до построения группы. Полные комбинации видимых признаков, которым соответствуют меньше пяти кандидатов, обобщаются или скрываются. Это снижает риск идентификации, но не гарантирует анонимность. Приватный псевдоним предпросмотра владельца использует отдельное назначение. Категория и денежная совместимость отсутствуют до получения данных от авторитетного источника; заявленный грейд не заменяет подтверждение. + +Кандидат читает настройки через `GET /api/v1/me/privacy`, предпросмотр - через `GET /api/v1/me/privacy/preview`, историю изменений - через `GET /api/v1/me/privacy/history`, а просмотры карточки - через `GET /api/v1/me/privacy/access-history`. Скрытые компании доступны через `GET /api/v1/me/privacy/hidden-organizations` и меняются через `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Публикация и статус поиска меняются через `PUT /api/v1/me/privacy/publication` и `PUT /api/v1/me/privacy/search-status`. Данные доступны только из текущей сессии кандидата, ответы имеют `Cache-Control: no-store`, а изменения требуют CSRF-токен сессии и точный разрешенный Origin. C2, публикация, статус поиска и скрытые компании независимы: один параметр не включает остальные. Поиск остается заявлением кандидата, а не согласием. + +Работодатель с подтвержденной учетной записью и активным членством читает карточку по `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Каждый запрос заново проверяет членство, действующее C2, публикацию, скрытие для этой компании и минимальный размер группы; успешный просмотр и расход квоты записываются в одной транзакции. Закрытая, отозванная, скрытая или подавленная карточка не раскрывается и отвечает так же, как неизвестный псевдоним. Кандидат видит записи об успешных просмотрах карточки в своей истории доступа. Операция чтения контактов и управление грантами C4 пока недоступны; карточка контактов не содержит. + Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/backend/cmd/questionnaire-fixture/main.go b/backend/cmd/questionnaire-fixture/main.go index a11ca8c..75739a1 100644 --- a/backend/cmd/questionnaire-fixture/main.go +++ b/backend/cmd/questionnaire-fixture/main.go @@ -4,17 +4,23 @@ package main import ( "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" "errors" "fmt" "os" "time" + "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/policy" ) const ( @@ -22,13 +28,15 @@ const ( fixtureTimeout = 90 * time.Second maxFixtureFamilies = 200 - fixtureBundleName = "e2e-questionnaire-bank" - fixtureAuthor = "operator:questionnaire-fixture-author" - fixtureReviewer = "operator:questionnaire-fixture-reviewer" - fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher") - fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener") - fixtureFamilyStem = "e2e-questionnaire-family-" - fixtureCategory = domain.AssessmentCategory("backend") + fixtureBundleName = "e2e-questionnaire-bank" + fixtureAuthor = "operator:questionnaire-fixture-author" + fixtureReviewer = "operator:questionnaire-fixture-reviewer" + fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher") + fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener") + fixtureFamilyStem = "e2e-questionnaire-family-" + fixtureCategory = domain.AssessmentCategory("backend") + trainingFamilyStem = "e2e-express-family-" + trainingCategory = "e2e-express" ) func main() { @@ -85,9 +93,16 @@ func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error { if occupied { return errors.New(location + " refuses existing backend openings or published families") } + trainingOccupied, err := questionnaireTrainingBankOccupied(ctx, pool) + if err != nil { + return errors.New(location + " could not inspect training bank state") + } + if trainingOccupied { + return errors.New(location + " refuses an existing training binding or published families") + } transactor := postgres.NewTransactor(pool) - currentPolicy, err := currentProductPolicy(ctx, transactor) + currentPolicy, err := publishFixturePolicy(ctx, transactor) if err != nil { if errors.Is(err, outbound.ErrPolicyVersionNotFound) { return errors.New(location + " requires a current product assessment policy") @@ -122,6 +137,156 @@ func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error { }); err != nil { return errors.New(location + " could not open the reviewed catalog mapping") } + if err := seedQuestionnaireTrainingBank(ctx, pool, bank, currentPolicy); err != nil { + return errors.New(location + " could not seed the reviewed express training bank") + } + return nil +} + +func questionnaireTrainingBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) { + var occupied bool + err := pool.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM assessment_training_bank_bindings WHERE category = $1 + ) OR EXISTS ( + SELECT 1 FROM assessment_families + WHERE category = $1 AND family_key LIKE $2 + )`, trainingCategory, trainingFamilyStem+"%").Scan(&occupied) + return occupied, err +} + +func seedQuestionnaireTrainingBank( + ctx context.Context, + pool *pgxpool.Pool, + bank *assessment.Bank, + productPolicy domain.PolicyVersion, +) error { + trainingPolicy := productPolicy.Policy().Assessment.Training + if trainingPolicy == nil { + return errors.New("current product policy has no explicit training mode") + } + count := int(trainingPolicy.DemoExpressItemCount) + if count < 1 || count > maxFixtureFamilies { + return errors.New("training item count is outside the fixture limit") + } + bundle, err := reviewedTrainingBundle(count) + if err != nil { + return errors.New("reviewed training family fixture is invalid") + } + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + return errors.New("could not import reviewed training families") + } + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + return errors.New("could not publish reviewed training family") + } + } + return seedQuestionnaireTrainingBinding(ctx, pool, productPolicy.ID().UUID(), bundle.Category, count) +} + +func reviewedTrainingBundle(count int) (assessment.Bundle, error) { + bundle, err := reviewedQuestionnaireBundle(count) + if err != nil { + return assessment.Bundle{}, err + } + bundle.Name = "e2e-express-training-bank" + bundle.Category = trainingCategory + for index := range bundle.Families { + bundle.Families[index].Key = fmt.Sprintf("%s%02d", trainingFamilyStem, index+1) + bundle.Families[index].Specialization = "rate-limiting" + } + if _, err := bundle.Drafts(); err != nil { + return assessment.Bundle{}, err + } + return bundle, nil +} + +func seedQuestionnaireTrainingBinding( + ctx context.Context, + pool *pgxpool.Pool, + policyID uuid.UUID, + category string, + itemCount int, +) error { + type manifestEntry struct { + FamilyKey string `json:"family_key"` + Version int32 `json:"version"` + ContentSHA256 string `json:"content_sha256"` + } + type familyRecord struct { + ID uuid.UUID + Entry manifestEntry + Hash []byte + } + rows, err := pool.Query(ctx, ` + SELECT id, family_key, version, content_sha256 + FROM assessment_families + WHERE category=$1 AND lifecycle='published' + ORDER BY family_key, version`, category) + if err != nil { + return errors.New("could not read published training families") + } + var families []familyRecord + for rows.Next() { + var family familyRecord + if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil { + rows.Close() + return errors.New("could not read a published training family") + } + family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash) + families = append(families, family) + } + if err := rows.Err(); err != nil { + rows.Close() + return errors.New("could not finish reading training families") + } + rows.Close() + if len(families) != itemCount { + return errors.New("published training family count does not match policy") + } + entries := make([]manifestEntry, len(families)) + canonical := []byte("lincodex.assessment.category-manifest.v1\x00") + for index, family := range families { + if len(family.Entry.FamilyKey) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size { + return errors.New("training family manifest entry is outside the supported range") + } + entries[index] = family.Entry + key := []byte(family.Entry.FamilyKey) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key))) + canonical = append(canonical, key...) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version)) + canonical = append(canonical, family.Hash...) + } + manifest, err := json.Marshal(entries) + if err != nil { + return errors.New("could not encode training family manifest") + } + manifestHash := sha256.Sum256(canonical) + transaction, err := pool.Begin(ctx) + if err != nil { + return errors.New("could not begin training binding transaction") + } + defer transaction.Rollback(ctx) + bindingID := uuid.New() + if _, err := transaction.Exec(ctx, ` + INSERT INTO assessment_training_bank_bindings ( + id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`, + bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil { + return errors.New("could not insert the training binding") + } + for index, family := range families { + if _, err := transaction.Exec(ctx, ` + INSERT INTO assessment_training_bank_binding_families ( + binding_id, ordinal, family_id, family_key, family_version, content_sha256 + ) VALUES ($1,$2,$3,$4,$5,$6)`, + bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil { + return errors.New("could not add a training binding family") + } + } + if err := transaction.Commit(ctx); err != nil { + return errors.New("could not commit the training binding") + } return nil } @@ -129,7 +294,7 @@ func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, e return domain.NewAssessmentCategoryCatalogMetadata( domain.SpecializationBackend, domain.GradeJunior, - []domain.TaskLanguageCode{domain.TaskLanguageGo}, + []domain.TaskLanguageCode{domain.TaskLanguageGo, domain.TaskLanguagePython}, ) } @@ -149,14 +314,38 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) ( return occupied, err } -func currentProductPolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) { +// The isolated browser fixture opts into the extended demo policy explicitly. +// Normal startup still seeds V1, and an operator's policy must never be replaced. +func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) { + initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + return domain.PolicyVersion{}, err + } var version domain.PolicyVersion - err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) if err != nil { return err } - version, err = unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime) + current, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime) + if err != nil { + return err + } + latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil { + return err + } + if current.Kind() != domain.PolicyKindDemo || current.DocumentHash() != initial.DocumentHash() || + current.Version() != 1 || current.ID() != latest.ID() { + return errors.New("questionnaire fixture refuses an operator-owned product policy") + } + version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV2(), + }) return err }) return version, err diff --git a/backend/cmd/questionnaire-fixture/main_test.go b/backend/cmd/questionnaire-fixture/main_test.go index b398994..e336536 100644 --- a/backend/cmd/questionnaire-fixture/main_test.go +++ b/backend/cmd/questionnaire-fixture/main_test.go @@ -79,8 +79,9 @@ func TestQuestionnaireCatalogMetadataUsesTheReviewedE2EProjection(t *testing.T) t.Fatalf("questionnaireCatalogMetadata() error = %v", err) } if metadata.Specialization() != domain.SpecializationBackend || metadata.Grade() != domain.GradeJunior || - len(metadata.TaskLanguages()) != 1 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo { - t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go", + len(metadata.TaskLanguages()) != 2 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo || + metadata.TaskLanguages()[1] != domain.TaskLanguagePython { + t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go+Python", metadata.Specialization(), metadata.Grade(), metadata.TaskLanguages()) } } diff --git a/backend/db/migrations/00024_create_assessment_attempts.sql b/backend/db/migrations/00024_create_assessment_attempts.sql new file mode 100644 index 0000000..fe719be --- /dev/null +++ b/backend/db/migrations/00024_create_assessment_attempts.sql @@ -0,0 +1,719 @@ +-- +goose Up +-- Assessment attempts pin their product policy, category opening or separate +-- training source, and generated item variants. Candidate answers are stored +-- separately from the immutable variant and never appear in idempotency rows. + +CREATE TABLE assessment_training_bank_bindings ( + id uuid NOT NULL, + category text NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + item_count integer NOT NULL, + manifest_sha256 bytea NOT NULL, + family_manifest jsonb NOT NULL, + reviewed_by text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_training_bank_bindings_pkey PRIMARY KEY (id), + CONSTRAINT assessment_training_bank_bindings_policy_manifest_key UNIQUE ( + category, product_policy_version_id, manifest_sha256 + ), + CONSTRAINT assessment_training_bank_bindings_category_format CHECK ( + category ~ '^[a-z][a-z0-9-]{1,47}$' + ), + CONSTRAINT assessment_training_bank_bindings_item_count CHECK ( + item_count BETWEEN 1 AND 20 + ), + CONSTRAINT assessment_training_bank_bindings_manifest_hash CHECK ( + octet_length(manifest_sha256) = 32 + ), + CONSTRAINT assessment_training_bank_bindings_manifest_object CHECK ( + jsonb_typeof(family_manifest) = 'array' + ), + CONSTRAINT assessment_training_bank_bindings_reviewer CHECK ( + char_length(reviewed_by) <= 128 + AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +CREATE TABLE assessment_training_bank_binding_families ( + binding_id uuid NOT NULL REFERENCES assessment_training_bank_bindings (id), + ordinal integer NOT NULL, + family_id uuid NOT NULL REFERENCES assessment_families (id), + family_key text NOT NULL, + family_version integer NOT NULL, + content_sha256 bytea NOT NULL, + CONSTRAINT assessment_training_bank_binding_families_pkey PRIMARY KEY (binding_id, ordinal), + CONSTRAINT assessment_training_bank_binding_families_family_key UNIQUE (binding_id, family_key), + CONSTRAINT assessment_training_bank_binding_families_ordinal CHECK (ordinal > 0), + CONSTRAINT assessment_training_bank_binding_families_version CHECK (family_version > 0), + CONSTRAINT assessment_training_bank_binding_families_hash CHECK (octet_length(content_sha256) = 32) +); + +-- A binding is accepted only for an explicit training policy and a category +-- not already opened for real assessments. The category advisory lock is the +-- same lock taken by the bank's publish, retire, and opening operations. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + policy_item_count integer; + current_product_policy_id uuid; +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.category, 0) + ); + + SELECT (document #>> '{assessment,training,demo_express_item_count}')::integer + INTO policy_item_count + FROM policy_versions + WHERE id = NEW.product_policy_version_id + AND policy_key = 'product'; + + IF policy_item_count IS NULL OR policy_item_count <> NEW.item_count THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_policy', + MESSAGE = 'training binding does not match explicit product policy'; + END IF; + + SELECT id INTO current_product_policy_id + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= clock_timestamp() + ORDER BY version DESC + LIMIT 1; + IF current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_current_policy', + MESSAGE = 'training binding must pin the current product policy'; + END IF; + + IF EXISTS ( + SELECT 1 FROM assessment_category_openings WHERE category = NEW.category + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint', + MESSAGE = 'training category already has a real opening'; + END IF; + + NEW.created_at := clock_timestamp(); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_guard +BEFORE INSERT ON assessment_training_bank_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_guard(); + +-- A real opening cannot consume a category reserved for training. Taking the +-- same lock in both directions closes the race between binding and opening. +-- +goose StatementBegin +CREATE FUNCTION assessment_real_opening_rejects_training_category() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.category, 0) + ); + + IF EXISTS ( + SELECT 1 FROM assessment_training_bank_bindings WHERE category = NEW.category + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint', + MESSAGE = 'real opening cannot use a training category'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_real_opening_rejects_training_category +BEFORE INSERT ON assessment_category_openings +FOR EACH ROW EXECUTE FUNCTION assessment_real_opening_rejects_training_category(); + +-- Each pinned training family must be reviewed, published, and in the +-- category reserved by its binding. No family row can later be replaced. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_family_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + binding assessment_training_bank_bindings%ROWTYPE; + family assessment_families%ROWTYPE; +BEGIN + SELECT * INTO STRICT binding + FROM assessment_training_bank_bindings + WHERE id = NEW.binding_id; + + SELECT * INTO STRICT family + FROM assessment_families + WHERE id = NEW.family_id; + + IF family.category <> binding.category OR family.family_key <> NEW.family_key OR + family.version <> NEW.family_version OR family.content_sha256 <> NEW.content_sha256 OR + family.lifecycle <> 'published' OR family.review_status <> 'approved' OR + family.reviewer IS NULL OR family.author = family.reviewer THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_family_reviewed', + MESSAGE = 'training family is not an approved published member of the binding'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_family_guard +BEFORE INSERT ON assessment_training_bank_binding_families +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_guard(); + +-- The family rows and canonical manifest must agree when the transaction +-- commits; inserts may arrive after the binding header in the same unit. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_complete() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + binding_id_value uuid; +BEGIN + binding_id_value := NEW.id; + PERFORM assessment_training_binding_assert_complete(binding_id_value); + + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_assert_complete(binding_id_value uuid) RETURNS void +LANGUAGE plpgsql AS $$ +DECLARE + expected_count integer; + actual_count integer; + actual_manifest jsonb; + family_manifest_value jsonb; +BEGIN + SELECT item_count, family_manifest INTO expected_count, family_manifest_value + FROM assessment_training_bank_bindings + WHERE id = binding_id_value; + + SELECT count(*)::integer INTO actual_count + FROM assessment_training_bank_binding_families + WHERE binding_id = binding_id_value; + + IF actual_count <> expected_count OR jsonb_array_length(family_manifest_value) <> expected_count THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_complete', + MESSAGE = 'training binding family count is incomplete'; + END IF; + + SELECT COALESCE(jsonb_agg( + jsonb_build_object( + 'family_key', family_key, + 'version', family_version, + 'content_sha256', encode(content_sha256, 'hex') + ) ORDER BY family_key, family_version + ), '[]'::jsonb) INTO actual_manifest + FROM assessment_training_bank_binding_families + WHERE binding_id = binding_id_value; + + IF actual_manifest <> family_manifest_value THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_manifest', + MESSAGE = 'training binding manifest does not match its families'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- The deferred child trigger prevents an extra family from being appended +-- after the header's own deferred completeness check was queued. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_family_complete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM assessment_training_binding_assert_complete(NEW.binding_id); + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER assessment_training_binding_complete +AFTER INSERT ON assessment_training_bank_bindings +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_complete(); + +CREATE CONSTRAINT TRIGGER assessment_training_binding_family_complete +AFTER INSERT ON assessment_training_bank_binding_families +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_complete(); + +-- Bindings and their family manifest are immutable once stored. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_training_binding_immutable', + MESSAGE = 'training bank bindings are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_training_bank_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change(); + +CREATE TRIGGER assessment_training_binding_family_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_training_bank_binding_families +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change(); + +CREATE TABLE assessment_attempts ( + id uuid NOT NULL, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + kind text NOT NULL, + mode text NOT NULL, + state text NOT NULL, + outcome text, + bank_category text NOT NULL, + specialization text, + target_grade text, + task_language text, + root_attempt_id uuid NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid REFERENCES policy_versions (id), + opening_id uuid REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea, + training_binding_id uuid REFERENCES assessment_training_bank_bindings (id), + training_manifest_sha256 bytea, + bank_version text NOT NULL, + algorithm_version text NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + chain_deadline timestamptz, + idle_timeout_seconds integer NOT NULL, + max_sessions integer NOT NULL, + sessions_used integer NOT NULL, + session_started_at timestamptz NOT NULL, + last_activity_at timestamptz NOT NULL, + version bigint NOT NULL, + ended_at timestamptz, + CONSTRAINT assessment_attempts_pkey PRIMARY KEY (id), + CONSTRAINT assessment_attempts_id_owner_key UNIQUE (id, user_id), + CONSTRAINT assessment_attempts_owner_root_fk FOREIGN KEY (root_attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT assessment_attempts_kind CHECK (kind IN ('root', 'corrective', 'demo_express')), + CONSTRAINT assessment_attempts_mode CHECK (mode IN ('demo_basic', 'adaptive', 'demo_express')), + CONSTRAINT assessment_attempts_state CHECK ( + state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', + 'completed', 'expired', 'insufficient_bank') + ), + CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined') + ), + CONSTRAINT assessment_attempts_track CHECK ( + ( + kind IN ('root', 'corrective') + AND mode IN ('demo_basic', 'adaptive') + AND specialization IS NOT NULL + AND specialization ~ '^[a-z][a-z0-9_-]{1,47}$' + AND target_grade IS NOT NULL + AND target_grade IN ('intern', 'junior', 'middle', 'senior') + AND (task_language IS NULL OR task_language IN ('go', 'python')) + AND grading_policy_version_id IS NOT NULL + AND opening_id IS NOT NULL + AND opening_manifest_sha256 IS NOT NULL + AND octet_length(opening_manifest_sha256) = 32 + AND training_binding_id IS NULL + AND training_manifest_sha256 IS NULL + AND chain_deadline IS NOT NULL + AND ( + (kind = 'root' AND root_attempt_id = id) + OR (kind = 'corrective' AND root_attempt_id <> id) + ) + ) OR ( + kind = 'demo_express' + AND mode = 'demo_express' + AND specialization IS NULL AND target_grade IS NULL AND task_language IS NULL + AND root_attempt_id = id + AND grading_policy_version_id IS NULL + AND opening_id IS NULL AND opening_manifest_sha256 IS NULL + AND training_binding_id IS NOT NULL + AND training_manifest_sha256 IS NOT NULL + AND octet_length(training_manifest_sha256) = 32 + AND chain_deadline IS NULL + ) + ), + CONSTRAINT assessment_attempts_policy_version_positive CHECK (product_policy_version > 0), + CONSTRAINT assessment_attempts_version_positive CHECK (version > 0), + CONSTRAINT assessment_attempts_session_limits CHECK ( + idle_timeout_seconds BETWEEN 60 AND 86400 + AND max_sessions BETWEEN 1 AND 10 + AND sessions_used BETWEEN 1 AND max_sessions + ), + CONSTRAINT assessment_attempts_timestamps CHECK ( + created_at <= updated_at + AND created_at <= session_started_at + AND session_started_at <= last_activity_at + AND last_activity_at <= updated_at + AND expires_at > created_at + AND (chain_deadline IS NULL OR (chain_deadline > created_at AND expires_at <= chain_deadline)) + AND (ended_at IS NULL OR (ended_at >= created_at AND ended_at >= last_activity_at AND ended_at <= updated_at)) + ), + CONSTRAINT assessment_attempts_state_stamp CHECK ( + (state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') + AND outcome IS NULL AND ended_at IS NULL) + OR (state IN ('expired', 'insufficient_bank') AND outcome IS NULL AND ended_at IS NOT NULL) + OR (state = 'completed' AND outcome IS NOT NULL AND ended_at IS NOT NULL) + ) +); + +-- A corrective attempt can only attach to an eligible terminal root owned by +-- the same candidate and for the same specialization. The application still +-- validates the full chain order and descending grades inside its transaction. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_root_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + root_attempt assessment_attempts%ROWTYPE; +BEGIN + IF NEW.kind <> 'corrective' THEN + RETURN NEW; + END IF; + + SELECT * INTO root_attempt + FROM assessment_attempts + WHERE id = NEW.root_attempt_id + FOR SHARE; + + IF NOT FOUND OR root_attempt.kind <> 'root' OR root_attempt.user_id <> NEW.user_id OR + root_attempt.specialization <> NEW.specialization OR + root_attempt.state NOT IN ('expired', 'completed') OR + (root_attempt.state = 'completed' AND root_attempt.outcome NOT IN ('not_confirmed', 'not_determined')) OR + root_attempt.chain_deadline IS NULL OR root_attempt.chain_deadline <= NEW.created_at OR + NEW.chain_deadline <> root_attempt.chain_deadline THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_root_eligibility', + MESSAGE = 'corrective attempt does not continue an eligible root'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_root_guard +BEFORE INSERT OR UPDATE ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_root_guard(); + +-- Verify the row refers to the exact current, reviewed opening or separately +-- reviewed training binding chosen by the transaction-bound bank service. +-- The caller holds the category advisory lock while it resolves and inserts. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_bank_pin_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + pinned_category text; + pinned_product_policy_id uuid; + pinned_grading_policy_id uuid; + pinned_manifest_sha256 bytea; + current_product_policy_id uuid; + current_product_policy_version integer; +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.bank_category, 0) + ); + + SELECT id, version INTO current_product_policy_id, current_product_policy_version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= NEW.created_at + ORDER BY version DESC + LIMIT 1; + IF NOT FOUND OR current_product_policy_id <> NEW.product_policy_version_id OR + current_product_policy_version <> NEW.product_policy_version THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_product_policy_pin', + MESSAGE = 'attempt must pin the effective product policy'; + END IF; + + IF NEW.kind = 'demo_express' THEN + SELECT category, product_policy_version_id, manifest_sha256 + INTO pinned_category, pinned_product_policy_id, pinned_manifest_sha256 + FROM assessment_training_bank_bindings + WHERE id = NEW.training_binding_id; + + IF NOT FOUND OR pinned_category <> NEW.bank_category OR + pinned_product_policy_id <> NEW.product_policy_version_id OR + pinned_manifest_sha256 <> NEW.training_manifest_sha256 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_training_binding_pin', + MESSAGE = 'training attempt does not match its reviewed binding'; + END IF; + ELSE + SELECT opening.category, opening.policy_version_id, catalog.published_manifest_sha256 + INTO pinned_category, pinned_grading_policy_id, pinned_manifest_sha256 + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS catalog ON catalog.opening_id = opening.id + WHERE opening.id = NEW.opening_id + AND NOT EXISTS ( + SELECT 1 FROM assessment_category_openings AS newer + WHERE newer.category = opening.category + AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id) + ); + + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin', + MESSAGE = 'real attempt opening is not current and reviewed'; + END IF; + + IF pinned_category <> NEW.bank_category OR + pinned_grading_policy_id <> NEW.grading_policy_version_id OR + pinned_manifest_sha256 <> NEW.opening_manifest_sha256 OR + current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin', + MESSAGE = 'real attempt does not match its current reviewed opening'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_bank_pin_guard +BEFORE INSERT ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_bank_pin_guard(); + +-- Commands may update lifecycle and session fields, but an attempt's owner, +-- selection, policy/bank pins, and deadlines never change after creation. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_immutable_pins_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (to_jsonb(NEW) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' - + 'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' - + 'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') OR + NEW.version <> OLD.version + 1 OR NEW.updated_at < OLD.updated_at THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_pins_immutable', + MESSAGE = 'assessment attempt pins are immutable and every transition increments version'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_immutable_pins_guard +BEFORE UPDATE ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_immutable_pins_guard(); + +CREATE INDEX assessment_attempts_candidate_created_idx +ON assessment_attempts (user_id, created_at DESC, id DESC); + +-- Corrective attempts belong to their root chain and share its specialization. +CREATE INDEX assessment_attempts_root_chain_idx +ON assessment_attempts (root_attempt_id, created_at, id); + +-- Active work is unique per candidate and real specialization. All nonterminal +-- lifecycle states stay in the index as later commands add them. +CREATE UNIQUE INDEX assessment_attempts_one_active_real_specialization +ON assessment_attempts (user_id, specialization) +WHERE kind IN ('root', 'corrective') + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize'); + +CREATE UNIQUE INDEX assessment_attempts_one_active_training +ON assessment_attempts (user_id) +WHERE kind = 'demo_express' + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize'); + +CREATE TABLE assessment_attempt_items ( + id uuid NOT NULL, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + ordinal integer NOT NULL, + family_id uuid NOT NULL REFERENCES assessment_families (id), + family_key text NOT NULL, + family_version integer NOT NULL, + family_content_sha256 bytea NOT NULL, + variant jsonb NOT NULL, + -- Keep canonical UTF-8 JSON bytes so schema-valid strings containing NUL + -- survive PostgreSQL storage; jsonb rejects \u0000 values. + answer bytea, + answered_at timestamptz, + CONSTRAINT assessment_attempt_items_pkey PRIMARY KEY (id), + CONSTRAINT assessment_attempt_items_ordinal_key UNIQUE (attempt_id, ordinal), + CONSTRAINT assessment_attempt_items_family_key UNIQUE (attempt_id, family_key), + CONSTRAINT assessment_attempt_items_ordinal CHECK (ordinal BETWEEN 1 AND 220), + CONSTRAINT assessment_attempt_items_family_version CHECK (family_version > 0), + CONSTRAINT assessment_attempt_items_family_hash CHECK (octet_length(family_content_sha256) = 32), + CONSTRAINT assessment_attempt_items_variant_object CHECK ( + jsonb_typeof(variant) = 'object' AND octet_length(variant::text) <= 1048576 + ), + CONSTRAINT assessment_attempt_items_answer_bound CHECK ( + answer IS NULL OR octet_length(answer) <= 524288 + ), + CONSTRAINT assessment_attempt_items_answer_stamp CHECK ( + (answer IS NULL) = (answered_at IS NULL) + ) +); + +CREATE INDEX assessment_attempt_items_family_usage_idx +ON assessment_attempt_items (family_id, attempt_id); + +-- A variant's identity and content are fixed at creation. Answering is a +-- one-way NULL -> value transition; replay is handled by the attempt outcome. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_item_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt assessment_attempts%ROWTYPE; + family assessment_families%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() <= 1 THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_delete_forbidden', + MESSAGE = 'assessment items can be removed only by account or attempt cascade'; + END IF; + RETURN OLD; + END IF; + + SELECT * INTO STRICT attempt + FROM assessment_attempts WHERE id = NEW.attempt_id; + SELECT * INTO STRICT family + FROM assessment_families WHERE id = NEW.family_id; + + IF family.family_key <> NEW.family_key OR family.version <> NEW.family_version OR + family.content_sha256 <> NEW.family_content_sha256 OR family.category <> attempt.bank_category THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_pin', + MESSAGE = 'assessment item family pin is inconsistent'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.ordinal <> OLD.ordinal OR + NEW.family_id <> OLD.family_id OR NEW.family_key <> OLD.family_key OR + NEW.family_version <> OLD.family_version OR NEW.family_content_sha256 <> OLD.family_content_sha256 OR + NEW.variant <> OLD.variant OR OLD.answer IS NOT NULL OR NEW.answer IS NULL OR NEW.answered_at IS NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_immutable', + MESSAGE = 'assessment item identity and variant are immutable'; + END IF; + IF NEW.answered_at < attempt.created_at OR NEW.answered_at >= attempt.expires_at THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_time', + MESSAGE = 'assessment answer time is outside the attempt deadline'; + END IF; + ELSIF TG_OP = 'INSERT' THEN + IF family.lifecycle <> 'published' OR family.review_status <> 'approved' OR + family.reviewer IS NULL OR family.author = family.reviewer THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_reviewed', + MESSAGE = 'assessment item family is not approved and published'; + END IF; + IF attempt.kind = 'demo_express' AND NOT EXISTS ( + SELECT 1 + FROM assessment_training_bank_binding_families AS member + WHERE member.binding_id = attempt.training_binding_id + AND member.family_id = NEW.family_id + AND member.family_key = NEW.family_key + AND member.family_version = NEW.family_version + AND member.content_sha256 = NEW.family_content_sha256 + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_training_member', + MESSAGE = 'training attempt item is not in its pinned binding'; + END IF; + IF NEW.answer IS NOT NULL OR NEW.answered_at IS NOT NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_initial', + MESSAGE = 'assessment items start without candidate answers'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_item_guard +BEFORE INSERT OR UPDATE OR DELETE ON assessment_attempt_items +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_item_guard(); + +-- Every idempotent response is a typed, allowlisted public read-model snapshot. +-- It never contains candidate answers, reference answers, seeds, family keys, +-- or private policy and opening identifiers. +CREATE TABLE assessment_attempt_idempotency_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + operation text NOT NULL, + status_code smallint NOT NULL, + problem_code text, + response_snapshot jsonb, + response_schema_version smallint NOT NULL DEFAULT 1, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_attempt_idempotency_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT assessment_attempt_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')), + CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + ), + CONSTRAINT assessment_attempt_idempotency_outcomes_response CHECK ( + response_snapshot IS NULL OR ( + jsonb_typeof(response_snapshot) = 'object' + AND octet_length(response_snapshot::text) <= 4194304 + ) + ), + CONSTRAINT assessment_attempt_idempotency_outcomes_schema CHECK (response_schema_version = 1) +); + +-- Keep committed command outcomes immutable; the generic 24-hour idempotency +-- purge may still delete them by cascading from idempotency_records. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_idempotency_outcome_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_idempotency_outcome_immutable', + MESSAGE = 'assessment idempotency outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_idempotency_outcome_refuse_update +BEFORE UPDATE ON assessment_attempt_idempotency_outcomes +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_idempotency_outcome_refuse_update(); + +-- +goose Down +DROP TRIGGER assessment_attempt_idempotency_outcome_refuse_update ON assessment_attempt_idempotency_outcomes; +DROP FUNCTION assessment_attempt_idempotency_outcome_refuse_update(); +DROP TABLE assessment_attempt_idempotency_outcomes; + +DROP TRIGGER assessment_attempt_item_guard ON assessment_attempt_items; +DROP FUNCTION assessment_attempt_item_guard(); +DROP TABLE assessment_attempt_items; +DROP TRIGGER assessment_attempt_root_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_root_guard(); +DROP TRIGGER assessment_attempt_bank_pin_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_bank_pin_guard(); +DROP TRIGGER assessment_attempt_immutable_pins_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_immutable_pins_guard(); +DROP INDEX assessment_attempts_one_active_training; +DROP INDEX assessment_attempts_one_active_real_specialization; +DROP INDEX assessment_attempts_root_chain_idx; +DROP INDEX assessment_attempts_candidate_created_idx; +DROP TABLE assessment_attempts; + +DROP TRIGGER assessment_training_binding_family_refuse_update_delete ON assessment_training_bank_binding_families; +DROP TRIGGER assessment_training_binding_refuse_update_delete ON assessment_training_bank_bindings; +DROP FUNCTION assessment_training_binding_refuse_change(); +DROP TRIGGER assessment_training_binding_complete ON assessment_training_bank_bindings; +DROP TRIGGER assessment_training_binding_family_complete ON assessment_training_bank_binding_families; +DROP FUNCTION assessment_training_binding_complete(); +DROP FUNCTION assessment_training_binding_family_complete(); +DROP FUNCTION assessment_training_binding_assert_complete(uuid); +DROP TRIGGER assessment_training_binding_family_guard ON assessment_training_bank_binding_families; +DROP FUNCTION assessment_training_binding_family_guard(); +DROP TRIGGER assessment_real_opening_rejects_training_category ON assessment_category_openings; +DROP FUNCTION assessment_real_opening_rejects_training_category(); +DROP TRIGGER assessment_training_binding_guard ON assessment_training_bank_bindings; +DROP FUNCTION assessment_training_binding_guard(); +DROP TABLE assessment_training_bank_binding_families; +DROP TABLE assessment_training_bank_bindings; diff --git a/backend/db/migrations/00025_create_support_cases.sql b/backend/db/migrations/00025_create_support_cases.sql new file mode 100644 index 0000000..b2bf9c1 --- /dev/null +++ b/backend/db/migrations/00025_create_support_cases.sql @@ -0,0 +1,385 @@ +-- +goose Up +-- Account-owned support snapshots store only typed object references. The +-- referenced records stay in their own bounded authorization scopes. +CREATE SEQUENCE support_case_number_seq + AS bigint + MINVALUE 1 + MAXVALUE 9999999999 + NO CYCLE; + +CREATE TABLE support_cases ( + id uuid NOT NULL, + case_number text NOT NULL, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + case_type text NOT NULL, + status text NOT NULL, + description text NOT NULL, + object_type text, + object_id uuid, + assessment_specialization text, + assessment_grade text, + complaint_reason text, + rubric_version integer, + rubric_opening_id uuid, + rubric_policy_version_id uuid, + target_business_days integer NOT NULL, + target_due_at timestamptz NOT NULL, + target_answered_at timestamptz, + target_policy_version integer NOT NULL, + target_calendar_version integer NOT NULL, + decision_outcome text, + decision_reason text, + decision_at timestamptz, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT support_cases_pkey PRIMARY KEY (id), + CONSTRAINT support_cases_number_key UNIQUE (case_number), + CONSTRAINT support_cases_number_format CHECK ( + case_number ~ '^SC-[0-9]{4}-[0-9]{6,10}$' + AND substring(case_number FROM 4 FOR 4)::integer = + EXTRACT(YEAR FROM created_at AT TIME ZONE 'UTC')::integer + ), + CONSTRAINT support_cases_case_type CHECK ( + case_type IN ('support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment') + ), + CONSTRAINT support_cases_status CHECK ( + status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed') + ), + CONSTRAINT support_cases_description CHECK ( + char_length(description) BETWEEN 1 AND 4000 + ), + CONSTRAINT support_cases_object_pair CHECK ( + (object_type IS NULL) = (object_id IS NULL) + ), + CONSTRAINT support_cases_object_type CHECK ( + object_type IS NULL OR object_type IN ('assessment_attempt', 'organization', 'invitation', 'support_case') + ), + CONSTRAINT support_cases_assessment_target_pair CHECK ( + (assessment_specialization IS NULL) = (assessment_grade IS NULL) + ), + CONSTRAINT support_cases_assessment_specialization CHECK ( + assessment_specialization IS NULL OR assessment_specialization IN ( + 'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa' + ) + ), + CONSTRAINT support_cases_assessment_grade CHECK ( + assessment_grade IS NULL OR assessment_grade IN ('intern', 'junior', 'middle', 'senior') + ), + CONSTRAINT support_cases_complaint_reason CHECK ( + complaint_reason IS NULL OR complaint_reason IN ( + 'organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other' + ) + ), + CONSTRAINT support_cases_rubric_version CHECK (rubric_version IS NULL OR rubric_version > 0), + CONSTRAINT support_cases_rubric_opening_fkey FOREIGN KEY (rubric_opening_id) + REFERENCES assessment_category_openings (id), + CONSTRAINT support_cases_rubric_policy_version_fkey FOREIGN KEY (rubric_policy_version_id) + REFERENCES policy_versions (id), + CONSTRAINT support_cases_rubric_pin_shape CHECK ( + (rubric_version IS NULL AND rubric_opening_id IS NULL AND rubric_policy_version_id IS NULL) + OR ( + case_type = 'manual_assessment' + AND rubric_version IS NOT NULL + AND rubric_opening_id IS NOT NULL + AND rubric_policy_version_id IS NOT NULL + ) + ), + CONSTRAINT support_cases_target_values CHECK ( + target_business_days BETWEEN 1 AND 60 + AND target_policy_version > 0 + AND target_calendar_version > 0 + AND target_due_at >= created_at + AND (target_answered_at IS NULL OR target_answered_at >= created_at) + ), + CONSTRAINT support_cases_decision_shape CHECK ( + (decision_outcome IS NULL AND decision_reason IS NULL AND decision_at IS NULL) + OR ( + decision_outcome IS NOT NULL + AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed') + AND decision_reason IS NOT NULL + AND char_length(decision_reason) BETWEEN 1 AND 4000 + AND decision_at IS NOT NULL + ) + ), + CONSTRAINT support_cases_timestamps CHECK ( + updated_at >= created_at + AND (target_answered_at IS NULL OR target_answered_at <= updated_at) + AND (decision_at IS NULL OR (decision_at >= created_at AND decision_at <= updated_at)) + ), + CONSTRAINT support_cases_fields_match_type CHECK ( + ( + case_type = 'support' + AND (complaint_reason IS NULL) + AND rubric_version IS NULL + AND assessment_specialization IS NULL + ) + OR ( + case_type = 'complaint' + AND object_type IS NOT NULL + AND object_type IN ('organization', 'invitation') + AND complaint_reason IS NOT NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + AND (complaint_reason NOT IN ('offer_content', 'salary_terms_violation') OR object_type = 'invitation') + ) + OR ( + case_type = 'grade_appeal' + AND object_type IS NOT NULL + AND object_type IN ('assessment_attempt', 'support_case') + AND complaint_reason IS NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + ) + OR ( + case_type = 'anticheat_appeal' + AND object_type IS NOT NULL + AND object_type = 'assessment_attempt' + AND complaint_reason IS NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + ) + OR ( + case_type = 'manual_assessment' + AND assessment_specialization IS NOT NULL + AND complaint_reason IS NULL + AND (object_type IS NULL OR object_type = 'assessment_attempt') + ) + ), + CONSTRAINT support_cases_decision_matches_type CHECK ( + decision_outcome IS NULL + OR (case_type = 'support' AND decision_outcome = 'answered') + OR (case_type = 'manual_assessment' AND decision_outcome = 'assessed') + OR ( + case_type IN ('complaint', 'grade_appeal', 'anticheat_appeal') + AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld') + ) + ), + CONSTRAINT support_cases_status_decision CHECK ( + (status = 'resolved') = (decision_outcome IS NOT NULL) + ) +); + +-- A stored rubric pin must name the immutable current opening for the exact +-- target and the grading-policy version used by automated assessment. +-- +goose StatementBegin +CREATE FUNCTION support_cases_rubric_pin_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + opening_policy_version_id uuid; + pinned_version integer; +BEGIN + IF NEW.rubric_version IS NULL THEN + RETURN NEW; + END IF; + + SELECT opening.policy_version_id, policy.version + INTO opening_policy_version_id, pinned_version + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id + JOIN policy_versions AS policy + ON policy.id = opening.policy_version_id + WHERE opening.id = NEW.rubric_opening_id + AND opening.policy_version_id = NEW.rubric_policy_version_id + AND binding.specialization = NEW.assessment_specialization + AND binding.grade = NEW.assessment_grade + AND policy.policy_key = 'product' + AND NOT EXISTS ( + SELECT 1 + FROM assessment_category_openings AS newer + WHERE newer.category = opening.category + AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id) + ) + AND opening.policy_version_id = ( + SELECT current_policy.id + FROM policy_versions AS current_policy + WHERE current_policy.policy_key = 'product' + AND current_policy.effective_at <= statement_timestamp() + ORDER BY current_policy.version DESC + LIMIT 1 + ); + + IF NOT FOUND OR opening_policy_version_id IS DISTINCT FROM NEW.rubric_policy_version_id + OR pinned_version IS DISTINCT FROM NEW.rubric_version THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', CONSTRAINT = 'support_cases_rubric_pin_consistency', + MESSAGE = 'support case rubric pin does not match its current reviewed opening'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_cases_rubric_pin_guard +BEFORE INSERT OR UPDATE OF rubric_version, rubric_opening_id, rubric_policy_version_id, + assessment_specialization, assessment_grade, created_at +ON support_cases +FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_guard(); + +-- Rubric evidence is fixed at creation even when case status and history later +-- change. +-- +goose StatementBegin +CREATE FUNCTION support_cases_rubric_pin_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (NEW.rubric_version, NEW.rubric_opening_id, NEW.rubric_policy_version_id) + IS DISTINCT FROM (OLD.rubric_version, OLD.rubric_opening_id, OLD.rubric_policy_version_id) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'support_cases_rubric_pin_immutable', + MESSAGE = 'support case rubric pin is immutable'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_cases_rubric_pin_immutable +BEFORE UPDATE ON support_cases +FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_immutable(); + +CREATE INDEX support_cases_owner_created_idx +ON support_cases (owner_id, created_at DESC, id DESC); + +-- An appeal is once per owner, appeal type, and target regardless of outcome. +CREATE UNIQUE INDEX support_cases_one_appeal_per_target +ON support_cases (owner_id, case_type, object_type, object_id) +WHERE case_type IN ('grade_appeal', 'anticheat_appeal'); + +CREATE UNIQUE INDEX support_cases_one_open_manual_assessment +ON support_cases (owner_id, assessment_specialization) +WHERE case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed'); + +CREATE UNIQUE INDEX support_cases_one_open_complaint_per_object +ON support_cases (owner_id, object_type, object_id) +WHERE case_type = 'complaint' AND status NOT IN ('resolved', 'closed'); + +-- Events are the append-only public history. No staff identity, private note, +-- evidence blob, or copied object data is present in this table. +CREATE TABLE support_case_events ( + case_id uuid NOT NULL REFERENCES support_cases (id) ON DELETE CASCADE, + sequence integer NOT NULL, + event_kind text NOT NULL, + actor_kind text NOT NULL, + occurred_at timestamptz NOT NULL, + status text, + message text, + CONSTRAINT support_case_events_pkey PRIMARY KEY (case_id, sequence), + CONSTRAINT support_case_events_sequence CHECK (sequence BETWEEN 1 AND 200), + CONSTRAINT support_case_events_kind CHECK ( + event_kind IN ('created', 'status_changed', 'reply', 'decision') + ), + CONSTRAINT support_case_events_actor CHECK (actor_kind IN ('user', 'support', 'system')), + CONSTRAINT support_case_events_status CHECK ( + status IS NULL OR status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed') + ), + CONSTRAINT support_case_events_message CHECK ( + message IS NULL OR ( + char_length(message) BETWEEN 1 AND 4000 + ) + ), + CONSTRAINT support_case_events_shape CHECK ( + (event_kind = 'created' AND actor_kind = 'user' AND status = 'submitted' AND message IS NULL) + OR (event_kind = 'status_changed' AND actor_kind IN ('support', 'system') AND status IS NOT NULL) + OR (event_kind = 'reply' AND actor_kind IN ('user', 'support') AND status IS NULL AND message IS NOT NULL) + OR (event_kind = 'decision' AND actor_kind = 'support' AND status = 'resolved' AND message IS NOT NULL) + ), + CONSTRAINT support_case_events_close_reason CHECK ( + status <> 'closed' OR (event_kind = 'status_changed' AND message IS NOT NULL) + ) +); + +-- Prevent rewriting event history while allowing account deletion cascades. +-- +goose StatementBegin +CREATE FUNCTION support_case_events_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'support_case_events_immutable', + MESSAGE = 'support case events are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_case_events_refuse_update_delete +BEFORE UPDATE OR DELETE ON support_case_events +FOR EACH ROW EXECUTE FUNCTION support_case_events_refuse_change(); + +-- The create result lives exactly as long as its generic scoped idempotency +-- record. Its original snapshot and late flag cannot be rewritten on replay. +CREATE TABLE support_case_create_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + outcome_kind text NOT NULL, + case_snapshot jsonb, + target_was_late boolean, + created_at timestamptz NOT NULL, + CONSTRAINT support_case_create_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT support_case_create_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT support_case_create_outcomes_kind CHECK ( + outcome_kind IN ('created', 'not_found', 'state_conflict') + ), + CONSTRAINT support_case_create_outcomes_snapshot CHECK ( + ( + outcome_kind = 'created' + AND case_snapshot IS NOT NULL + AND jsonb_typeof(case_snapshot) = 'object' + AND octet_length(case_snapshot::text) <= 1048576 + AND target_was_late IS NOT NULL + ) OR ( + outcome_kind IN ('not_found', 'state_conflict') + AND case_snapshot IS NULL + AND target_was_late IS NULL + ) + ) +); + +-- A live idempotent result cannot change between the original response and a +-- replay. Expiry cleanup may still delete it through its parent record. +-- +goose StatementBegin +CREATE FUNCTION support_case_create_outcomes_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'support_case_create_outcomes_immutable', + MESSAGE = 'support case create outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_case_create_outcomes_refuse_update +BEFORE UPDATE ON support_case_create_outcomes +FOR EACH ROW EXECUTE FUNCTION support_case_create_outcomes_refuse_update(); + +-- Request events retain the maximum supported 24-hour window, not merely the +-- current policy's window. Rows are pruned in small batches by each request. +CREATE TABLE support_case_request_events ( + id bigint GENERATED ALWAYS AS IDENTITY, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + requested_at timestamptz NOT NULL, + CONSTRAINT support_case_request_events_pkey PRIMARY KEY (id) +); + +CREATE INDEX support_case_request_events_owner_time_idx +ON support_case_request_events (owner_id, requested_at, id); + +-- +goose Down +DROP TABLE support_case_request_events; +DROP TRIGGER support_cases_rubric_pin_immutable ON support_cases; +DROP FUNCTION support_cases_rubric_pin_immutable(); +DROP TRIGGER support_cases_rubric_pin_guard ON support_cases; +DROP FUNCTION support_cases_rubric_pin_guard(); +DROP TRIGGER support_case_create_outcomes_refuse_update ON support_case_create_outcomes; +DROP FUNCTION support_case_create_outcomes_refuse_update(); +DROP TABLE support_case_create_outcomes; +DROP TRIGGER support_case_events_refuse_update_delete ON support_case_events; +DROP FUNCTION support_case_events_refuse_change(); +DROP TABLE support_case_events; +DROP INDEX support_cases_one_open_complaint_per_object; +DROP INDEX support_cases_one_open_manual_assessment; +DROP INDEX support_cases_one_appeal_per_target; +DROP INDEX support_cases_owner_created_idx; +DROP TABLE support_cases; +DROP SEQUENCE support_case_number_seq; diff --git a/backend/db/migrations/00026_create_organization_need_creation_results.sql b/backend/db/migrations/00026_create_organization_need_creation_results.sql new file mode 100644 index 0000000..e3999ef --- /dev/null +++ b/backend/db/migrations/00026_create_organization_need_creation_results.sql @@ -0,0 +1,97 @@ +-- +goose Up +-- Store the original public create response alongside the generic +-- idempotency record. A new reservation may replace this snapshot only after +-- the 24-hour logical replay window expires; bounded purge removes it with +-- the idempotency row. The live need is intentionally not a foreign key. +-- jsonb::text adds structural whitespace, so these checks allow a bounded +-- 8 KiB representation margin after the compact application-level limits. +ALTER TABLE organization_need_versions + DROP CONSTRAINT organization_need_versions_snapshot_shape, + ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version'] + AND jsonb_typeof(snapshot -> 'id') = 'string' + AND snapshot ->> 'id' = need_id::text + AND jsonb_typeof(snapshot -> 'organization_id') = 'string' + AND snapshot ->> 'organization_id' = organization_id::text + AND jsonb_typeof(snapshot -> 'version') = 'number' + AND snapshot ->> 'version' = version::text + AND jsonb_typeof(snapshot -> 'requirements_version') = 'number' + AND CASE + WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$' + THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version + ELSE FALSE + END + AND octet_length(snapshot::text) <= 270336 + ); + +CREATE TABLE organization_need_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT organization_need_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT organization_need_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT organization_need_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT organization_need_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['need', 'readiness', 'recommendations'] + AND octet_length(snapshot::text) <= 532480 + ) +); + +-- +goose Down +-- Rolling back must not invalidate a response replay that is still within its +-- logical window, or remove historical need snapshots that the old bound +-- cannot represent. Expired replay rows may remain until bounded purge runs. +-- The idempotency lock blocks writes across the shared table, so operators +-- run this rollback with writing processes stopped. +LOCK TABLE idempotency_records IN ACCESS EXCLUSIVE MODE; +LOCK TABLE organization_need_versions IN ACCESS EXCLUSIVE MODE; +LOCK TABLE organization_need_creation_results IN ACCESS EXCLUSIVE MODE; + +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organization_need_creation_results AS result + INNER JOIN idempotency_records AS record USING (scope_hash) + WHERE record.expires_at > clock_timestamp() + ) THEN + RAISE EXCEPTION 'cannot roll back migration 00026 while live need creation replays remain'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM organization_need_versions + WHERE octet_length(snapshot::text) > 262144 + ) THEN + RAISE EXCEPTION 'cannot roll back migration 00026 while need snapshots exceed the prior storage bound'; + END IF; +END +$$; +-- +goose StatementEnd + +DROP TABLE organization_need_creation_results; +ALTER TABLE organization_need_versions + DROP CONSTRAINT organization_need_versions_snapshot_shape, + ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version'] + AND jsonb_typeof(snapshot -> 'id') = 'string' + AND snapshot ->> 'id' = need_id::text + AND jsonb_typeof(snapshot -> 'organization_id') = 'string' + AND snapshot ->> 'organization_id' = organization_id::text + AND jsonb_typeof(snapshot -> 'version') = 'number' + AND snapshot ->> 'version' = version::text + AND jsonb_typeof(snapshot -> 'requirements_version') = 'number' + AND CASE + WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$' + THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version + ELSE FALSE + END + AND octet_length(snapshot::text) <= 262144 + ); diff --git a/backend/db/migrations/00027_expand_candidate_card_fields.sql b/backend/db/migrations/00027_expand_candidate_card_fields.sql new file mode 100644 index 0000000..2e36258 --- /dev/null +++ b/backend/db/migrations/00027_expand_candidate_card_fields.sql @@ -0,0 +1,64 @@ +-- +goose Up +-- TASK-089 adds separately chosen opt-in groups to the anonymous card. The +-- publication and event constraints call this function, so replacing it +-- changes the accepted contract without rewriting any saved field set. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 9 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'salary_compatibility', 'self_assessment', 'soft_skills', + 'stack', 'work_formats' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- +goose Down +-- Do not strand stored publication or immutable history rows outside the old +-- contract. An operator must close/remove the newer publications through the +-- normal product workflow before this migration can be rolled back. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM candidate_publications + WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text [] + ) OR EXISTS ( + SELECT 1 + FROM candidate_privacy_events + WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text [] + ) THEN + RAISE EXCEPTION 'candidate card opt-in fields are still referenced by publication history'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 6 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'soft_skills', 'stack' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd diff --git a/backend/db/migrations/00028_create_assessment_signals.sql b/backend/db/migrations/00028_create_assessment_signals.sql new file mode 100644 index 0000000..9df2463 --- /dev/null +++ b/backend/db/migrations/00028_create_assessment_signals.sql @@ -0,0 +1,186 @@ +-- +goose Up +-- Signal storage is a separate, bounded side channel. It contains only +-- client-reported timing and byte counts, never answer or clipboard content. +-- Writes take the generic idempotency scope, C3 consent row, then attempt row; +-- the event trigger's parent lock is reentrant inside that same transaction. + +ALTER TABLE assessment_attempt_items +ADD CONSTRAINT assessment_attempt_items_attempt_id_id_key UNIQUE (attempt_id, id); + +CREATE TABLE assessment_signal_batches ( + id uuid NOT NULL, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + received_at timestamptz NOT NULL, + event_count integer NOT NULL, + CONSTRAINT assessment_signal_batches_pkey PRIMARY KEY (id), + CONSTRAINT assessment_signal_batches_attempt_id_id_key UNIQUE (attempt_id, id), + CONSTRAINT assessment_signal_batches_event_count CHECK (event_count BETWEEN 1 AND 50) +); + +CREATE INDEX assessment_signal_batches_attempt_received_idx +ON assessment_signal_batches (attempt_id, received_at, id); + +-- Direct edits and deletes would invalidate accepted receipt counts. The +-- nested delete issued by the attempt foreign-key cascade is the only delete +-- path while a batch exists. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_batch_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_batches_immutable', + MESSAGE = 'assessment signal batches are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_batch_immutable +BEFORE UPDATE OR DELETE ON assessment_signal_batches +FOR EACH ROW EXECUTE FUNCTION assessment_signal_batch_immutable(); + +CREATE TABLE assessment_signal_events ( + batch_id uuid NOT NULL, + attempt_id uuid NOT NULL, + ordinal integer NOT NULL, + item_instance_id uuid NOT NULL, + kind text NOT NULL, + occurred_at timestamptz NOT NULL, + duration_ms integer, + size_bytes integer, + CONSTRAINT assessment_signal_events_pkey PRIMARY KEY (batch_id, ordinal), + CONSTRAINT assessment_signal_events_batch_attempt_fk FOREIGN KEY (attempt_id, batch_id) + REFERENCES assessment_signal_batches (attempt_id, id) ON DELETE CASCADE, + CONSTRAINT assessment_signal_events_item_attempt_fk FOREIGN KEY (attempt_id, item_instance_id) + REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE, + CONSTRAINT assessment_signal_events_ordinal CHECK (ordinal BETWEEN 1 AND 50), + CONSTRAINT assessment_signal_events_kind CHECK ( + kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit') + ), + CONSTRAINT assessment_signal_events_measurement CHECK ( + (kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL) + OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647) + OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL) + ) +); + +CREATE INDEX assessment_signal_events_attempt_idx +ON assessment_signal_events (attempt_id, batch_id, ordinal); + +-- Serialize capacity and lifecycle checks on the same attempt row used by the +-- usecase. The application stores a whole-batch saturated receipt before this +-- trigger is reached; the trigger is a backstop for other database writers. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_event_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt_kind text; + attempt_state text; + attempt_expires_at timestamptz; + existing_count bigint; +BEGIN + SELECT kind, state, expires_at + INTO attempt_kind, attempt_state, attempt_expires_at + FROM assessment_attempts + WHERE id = NEW.attempt_id + FOR UPDATE; + + IF attempt_kind NOT IN ('root', 'corrective') + OR attempt_state NOT IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') + OR attempt_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_active', + MESSAGE = 'assessment attempt cannot accept signal events'; + END IF; + + SELECT count(*) INTO existing_count + FROM assessment_signal_events + WHERE attempt_id = NEW.attempt_id; + + IF existing_count >= 10000 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_capacity', + MESSAGE = 'assessment attempt signal capacity is full'; + END IF; + + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_event_guard +BEFORE INSERT ON assessment_signal_events +FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_guard(); + +-- Events are immutable. Only nested foreign-key cascades may delete them. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_event_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_events_immutable', + MESSAGE = 'assessment signal events are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_event_immutable +BEFORE UPDATE OR DELETE ON assessment_signal_events +FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_immutable(); + +CREATE TABLE assessment_signal_idempotency_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + status text NOT NULL, + accepted_events integer NOT NULL, + received_at timestamptz NOT NULL, + CONSTRAINT assessment_signal_idempotency_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT assessment_signal_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT assessment_signal_idempotency_outcomes_status CHECK ( + (status = 'accepted' AND accepted_events BETWEEN 1 AND 50) + OR (status = 'saturated' AND accepted_events = 0) + ) +); + +CREATE INDEX assessment_signal_idempotency_outcomes_attempt_received_idx +ON assessment_signal_idempotency_outcomes (attempt_id, received_at, scope_hash); + +-- Expired scope replacement and idempotency cleanup may delete an outcome, +-- but a live response snapshot cannot be rewritten. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_idempotency_outcome_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_idempotency_outcomes_immutable', + MESSAGE = 'assessment signal outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_idempotency_outcome_immutable +BEFORE UPDATE ON assessment_signal_idempotency_outcomes +FOR EACH ROW EXECUTE FUNCTION assessment_signal_idempotency_outcome_immutable(); + +-- +goose Down +DROP TRIGGER assessment_signal_idempotency_outcome_immutable ON assessment_signal_idempotency_outcomes; +DROP FUNCTION assessment_signal_idempotency_outcome_immutable(); +DROP INDEX assessment_signal_idempotency_outcomes_attempt_received_idx; +DROP TABLE assessment_signal_idempotency_outcomes; +DROP TRIGGER assessment_signal_event_immutable ON assessment_signal_events; +DROP FUNCTION assessment_signal_event_immutable(); +DROP TRIGGER assessment_signal_event_guard ON assessment_signal_events; +DROP FUNCTION assessment_signal_event_guard(); +DROP INDEX assessment_signal_events_attempt_idx; +DROP TABLE assessment_signal_events; +DROP TRIGGER assessment_signal_batch_immutable ON assessment_signal_batches; +DROP FUNCTION assessment_signal_batch_immutable(); +DROP INDEX assessment_signal_batches_attempt_received_idx; +DROP TABLE assessment_signal_batches; +ALTER TABLE assessment_attempt_items +DROP CONSTRAINT assessment_attempt_items_attempt_id_id_key; diff --git a/backend/db/migrations/00029_expand_assessment_command_outcomes.sql b/backend/db/migrations/00029_expand_assessment_command_outcomes.sql new file mode 100644 index 0000000..17be92f --- /dev/null +++ b/backend/db/migrations/00029_expand_assessment_command_outcomes.sql @@ -0,0 +1,203 @@ +-- +goose Up +-- Assessment completion supports the deliberately separate express outcome, +-- and answers/finalization store immutable public responses for key replay. + +ALTER TABLE assessment_attempts + DROP CONSTRAINT assessment_attempts_outcome, + ADD CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined', 'demonstration') + ); + +ALTER TABLE assessment_attempt_idempotency_outcomes + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status, + ADD COLUMN pending_item_ids uuid[] NOT NULL DEFAULT '{}'::uuid[], + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK ( + operation IN ('create', 'session', 'answer', 'finalize') + ), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation IN ('answer', 'finalize') AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation IN ('answer', 'finalize') AND status_code = 404 AND problem_code = 'not_found' AND response_snapshot IS NULL) + OR (operation = 'answer' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL AND cardinality(pending_item_ids) = 0) + OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL) + ), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items CHECK ( + cardinality(pending_item_ids) <= 220 AND array_position(pending_item_ids, NULL) IS NULL AND + (cardinality(pending_item_ids) = 0 OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict')) + ); + +-- A completed result is stored once with its exact score, rationale, and +-- pinned inputs. The public projection has no answer keys or submitted answers. +CREATE TABLE assessment_attempt_results ( + attempt_id uuid NOT NULL, + user_id uuid NOT NULL, + result_snapshot jsonb NOT NULL, + schema_version smallint NOT NULL DEFAULT 1, + kind text NOT NULL, + mode text NOT NULL, + outcome text NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid REFERENCES policy_versions (id), + opening_id uuid REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea, + training_binding_id uuid REFERENCES assessment_training_bank_bindings (id), + training_manifest_sha256 bytea, + bank_version text NOT NULL, + algorithm_version text NOT NULL, + rationale_rule text NOT NULL, + pass_mark_basis_points integer, + scored_items smallint, + raw_score smallint, + pass_points smallint, + decided_at timestamptz NOT NULL, + CONSTRAINT assessment_attempt_results_pkey PRIMARY KEY (attempt_id), + CONSTRAINT assessment_attempt_results_owner_fk FOREIGN KEY (attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1), + CONSTRAINT assessment_attempt_results_snapshot CHECK ( + jsonb_typeof(result_snapshot) = 'object' AND octet_length(result_snapshot::text) <= 65536 AND + NOT (result_snapshot ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) AND + NOT ((result_snapshot->'attempt') ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) + ), + CONSTRAINT assessment_attempt_results_versions CHECK ( + product_policy_version > 0 AND bank_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' AND + algorithm_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' + ), + CONSTRAINT assessment_attempt_results_decision CHECK ( + (kind IN ('root', 'corrective') AND mode = 'demo_basic' AND outcome IN ('confirmed', 'not_confirmed') + AND rationale_rule = 'demo_basic_pass_mark' + AND grading_policy_version_id IS NOT NULL AND opening_id IS NOT NULL + AND opening_manifest_sha256 IS NOT NULL AND octet_length(opening_manifest_sha256) = 32 + AND training_binding_id IS NULL AND training_manifest_sha256 IS NULL + AND pass_mark_basis_points BETWEEN 1 AND 10000 + AND scored_items IS NOT NULL AND scored_items BETWEEN 1 AND 100 + AND raw_score IS NOT NULL AND raw_score BETWEEN 0 AND scored_items + AND pass_points IS NOT NULL AND pass_points BETWEEN 1 AND scored_items + AND pass_points = ((scored_items * pass_mark_basis_points + 9999) / 10000) + AND ((outcome = 'confirmed') = (raw_score >= pass_points))) + OR (kind = 'demo_express' AND mode = 'demo_express' AND outcome = 'demonstration' + AND rationale_rule = 'demonstration_only' + AND grading_policy_version_id IS NULL AND opening_id IS NULL AND opening_manifest_sha256 IS NULL + AND training_binding_id IS NOT NULL AND training_manifest_sha256 IS NOT NULL + AND octet_length(training_manifest_sha256) = 32 AND pass_mark_basis_points IS NULL + AND scored_items IS NULL AND raw_score IS NULL AND pass_points IS NULL) + ) +); + +-- Keep the decision row bound to the completed attempt and exact pinned inputs. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt assessment_attempts%ROWTYPE; +BEGIN + SELECT * INTO attempt + FROM assessment_attempts + WHERE id = NEW.attempt_id AND user_id = NEW.user_id + FOR SHARE; + + IF NOT FOUND OR attempt.state <> 'completed' OR attempt.kind <> NEW.kind OR attempt.mode <> NEW.mode OR + attempt.outcome <> NEW.outcome OR attempt.product_policy_version_id <> NEW.product_policy_version_id OR + attempt.product_policy_version <> NEW.product_policy_version OR attempt.grading_policy_version_id IS DISTINCT FROM NEW.grading_policy_version_id OR + attempt.opening_id IS DISTINCT FROM NEW.opening_id OR attempt.opening_manifest_sha256 IS DISTINCT FROM NEW.opening_manifest_sha256 OR + attempt.training_binding_id IS DISTINCT FROM NEW.training_binding_id OR attempt.training_manifest_sha256 IS DISTINCT FROM NEW.training_manifest_sha256 OR + attempt.bank_version <> NEW.bank_version OR attempt.algorithm_version <> NEW.algorithm_version OR + attempt.ended_at IS DISTINCT FROM NEW.decided_at OR + (NEW.result_snapshot->>'outcome') IS DISTINCT FROM NEW.outcome OR + (NEW.result_snapshot->>'decided_at')::timestamptz IS DISTINCT FROM NEW.decided_at OR + (NEW.result_snapshot->'attempt'->>'id')::uuid IS DISTINCT FROM NEW.attempt_id OR + (NEW.result_snapshot->'attempt'->>'kind') IS DISTINCT FROM NEW.kind OR + (NEW.result_snapshot->'attempt'->>'mode') IS DISTINCT FROM NEW.mode OR + (NEW.result_snapshot->'pins'->>'product_policy_version_id')::uuid IS DISTINCT FROM NEW.product_policy_version_id OR + (NEW.result_snapshot->'pins'->>'product_policy_version')::integer IS DISTINCT FROM NEW.product_policy_version OR + (NEW.result_snapshot->'pins'->>'bank_version') IS DISTINCT FROM NEW.bank_version OR + (NEW.result_snapshot->'pins'->>'algorithm_version') IS DISTINCT FROM NEW.algorithm_version OR + (NEW.result_snapshot->'pins'->>'opening_id')::uuid IS DISTINCT FROM NEW.opening_id OR + decode(NEW.result_snapshot->'pins'->>'opening_manifest_sha256', 'hex') IS DISTINCT FROM NEW.opening_manifest_sha256 OR + (NEW.result_snapshot->'pins'->>'training_binding_id')::uuid IS DISTINCT FROM NEW.training_binding_id OR + decode(NEW.result_snapshot->'pins'->>'training_manifest_sha256', 'hex') IS DISTINCT FROM NEW.training_manifest_sha256 OR + (NEW.result_snapshot->'rationale'->>'rule') IS DISTINCT FROM NEW.rationale_rule OR + (NEW.kind IN ('root', 'corrective') AND ( + (NEW.result_snapshot->'basic_score'->>'points')::smallint IS DISTINCT FROM NEW.raw_score OR + (NEW.result_snapshot->'basic_score'->>'max_points')::smallint IS DISTINCT FROM NEW.scored_items OR + (NEW.result_snapshot->'basic_score'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points OR + (NEW.result_snapshot->'rationale'->>'pass_mark_basis_points')::integer IS DISTINCT FROM NEW.pass_mark_basis_points OR + (NEW.result_snapshot->'rationale'->>'scored_items')::smallint IS DISTINCT FROM NEW.scored_items OR + (NEW.result_snapshot->'rationale'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points)) OR + (NEW.kind = 'demo_express' AND NEW.result_snapshot ? 'basic_score') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_snapshot_match', + MESSAGE = 'assessment result does not match its completed attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_guard +BEFORE INSERT ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_guard(); + +-- Results cannot be overwritten or deleted independently of owner deletion. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_refuse_mutation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_result_immutable', + MESSAGE = 'assessment result snapshots are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_refuse_mutation +BEFORE UPDATE OR DELETE ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_refuse_mutation(); + +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM assessment_attempts WHERE outcome = 'demonstration' + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_idempotency_outcomes WHERE operation IN ('answer', 'finalize') + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_results + ) THEN + RAISE EXCEPTION 'assessment command data uses migration 00029 and must be retained'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER assessment_attempt_result_refuse_mutation ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_refuse_mutation(); +DROP TRIGGER assessment_attempt_result_guard ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_guard(); +DROP TABLE assessment_attempt_results; + +ALTER TABLE assessment_attempt_idempotency_outcomes + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items, + DROP COLUMN pending_item_ids, + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + ); + +ALTER TABLE assessment_attempts + DROP CONSTRAINT assessment_attempts_outcome, + ADD CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined') + ); diff --git a/backend/db/migrations/00030_create_candidate_card_access_events.sql b/backend/db/migrations/00030_create_candidate_card_access_events.sql new file mode 100644 index 0000000..e3e354a --- /dev/null +++ b/backend/db/migrations/00030_create_candidate_card_access_events.sql @@ -0,0 +1,168 @@ +-- +goose Up +-- Immutable audit records for employer reads of anonymous cards and, when a +-- future grant-backed operation exists, selected contact fields. The table +-- contains identifiers and field codes only, never the viewed content. + +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + cardinality(field_codes) BETWEEN 0 AND 6 + AND array_position(field_codes, NULL) IS NULL + AND field_codes = ARRAY( + SELECT DISTINCT code COLLATE "C" + FROM unnest(field_codes) AS code + ORDER BY code COLLATE "C" + ) + AND ( + ( + kind = 'card_viewed' + AND field_codes <@ ARRAY[ + 'categories', 'experience', 'salary_compatibility', + 'self_assessment', 'stack', 'work_formats' + ]::text [] + ) + OR ( + kind = 'contact_read' + AND cardinality(field_codes) BETWEEN 1 AND 4 + AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + ) + ); +$$; +-- +goose StatementEnd + +CREATE TABLE candidate_card_access_events ( + id uuid NOT NULL, + candidate_id uuid NOT NULL, + organization_id uuid NOT NULL, + actor_id uuid, + kind text NOT NULL, + field_codes text [] NOT NULL, + occurred_at timestamptz NOT NULL, + CONSTRAINT candidate_card_access_events_pkey PRIMARY KEY (id), + CONSTRAINT candidate_card_access_events_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_card_access_events_organization_fkey FOREIGN KEY (organization_id) + REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT candidate_card_access_events_actor_fkey FOREIGN KEY (actor_id) + REFERENCES users (id) ON DELETE SET NULL, + CONSTRAINT candidate_card_access_events_kind_known CHECK ( + kind IN ('card_viewed', 'contact_read') + ), + CONSTRAINT candidate_card_access_events_fields_valid CHECK ( + candidate_card_access_fields_are_valid(kind, field_codes) + ) +); + +CREATE INDEX candidate_card_access_events_candidate_occurred_idx +ON candidate_card_access_events (candidate_id, occurred_at DESC, id DESC); + +CREATE INDEX candidate_card_access_events_organization_occurred_idx +ON candidate_card_access_events (organization_id, occurred_at DESC, id DESC); + +-- Records cannot be altered after insertion. Deletion is allowed only for +-- unverified-account cleanup; confirmed-account history remains evidence. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + -- Actor deletion may anonymize the foreign key while preserving every + -- other part of the historical event. + IF pg_trigger_depth() > 1 + AND OLD.actor_id IS NOT NULL + AND NEW.actor_id IS NULL + AND NEW.id IS NOT DISTINCT FROM OLD.id + AND NEW.candidate_id IS NOT DISTINCT FROM OLD.candidate_id + AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id + AND NEW.kind IS NOT DISTINCT FROM OLD.kind + AND NEW.field_codes IS NOT DISTINCT FROM OLD.field_codes + AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_immutable', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access events are append-only'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_refuse_update +BEFORE UPDATE ON candidate_card_access_events +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_update(); + +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.candidate_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_refuse_delete +BEFORE DELETE ON candidate_card_access_events +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_delete(); + +-- Protect a confirmed account from a direct DELETE that would otherwise +-- cascade away its access history. The unverified registration cleanup may +-- still remove those accounts and their records. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_protect_account() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.email_verified_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM candidate_card_access_events + WHERE candidate_card_access_events.candidate_id = OLD.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'users', + MESSAGE = 'confirmed account has retained card access history'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_protect_account +BEFORE DELETE ON users +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_protect_account(); + +-- +goose Down +-- Do not remove durable access evidence as a side effect of rolling back the +-- schema. Operators must export or explicitly resolve retained history first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM candidate_card_access_events) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access history must be retained before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER candidate_card_access_events_protect_account ON users; +DROP FUNCTION candidate_card_access_events_protect_account(); +DROP TRIGGER candidate_card_access_events_refuse_delete ON candidate_card_access_events; +DROP FUNCTION candidate_card_access_events_refuse_delete(); +DROP TRIGGER candidate_card_access_events_refuse_update ON candidate_card_access_events; +DROP FUNCTION candidate_card_access_events_refuse_update(); +DROP TABLE candidate_card_access_events; +DROP FUNCTION candidate_card_access_fields_are_valid(text, text []); diff --git a/backend/db/privacy_queries_test.go b/backend/db/privacy_queries_test.go index f31d16d..642b335 100644 --- a/backend/db/privacy_queries_test.go +++ b/backend/db/privacy_queries_test.go @@ -11,24 +11,28 @@ import ( // directPublicationReaders are the only queries that may name the table // candidate_publications. The first three are the candidate's own settings -// queries; every read on behalf of an organization must go through the view -// candidate_effective_publications (published and backed by an unrevoked C2) -// and exclude the hidden organizations, as ReadPublicationVisibleToOrganization -// does. A new query that reads the table directly fails this test, so it -// cannot leak a closed or revoked publication by accident. +// queries; the remaining reads are narrowly scoped lock/recheck operations +// that require current C2. Organization reads also exclude hidden +// organizations, and candidate preview reads remain owner-scoped. A new +// query that reads the table directly fails this test until it is reviewed. // // Only queries/*.sql are covered: the project keeps SQL in sqlc queries and // migrations, and the standards forbid raw SQL in Go code. var directPublicationReaders = []string{ + "ReadCandidatePrivacySettings", "ReadCandidatePublication", "InsertCandidatePublication", "UpdateCandidatePublication", } var ownerScopedPublicationQueries = []string{ + "LockPublicationForCandidatePreview", + "LockVisiblePublicationForView", "LockCandidatePublicationForConsentRevocation", } +var ownerPreviewQueries = []string{"ReadCandidateViewSourceForPreview"} + var ( // sqlc accepts both comment forms and tolerates trailing whitespace. queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`) @@ -66,11 +70,11 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { // Comments may name the table; statements may not. statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") name := text[header[2]:header[3]] + statements[name] = strings.Join(strings.Fields(statement), " ") if publicationTableName.MatchString(statement) { found = append(found, name) - statements[name] = strings.Join(strings.Fields(statement), " ") } - if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) { + if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) && !slices.Contains(ownerPreviewQueries, name) { t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name) } } @@ -81,9 +85,6 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { if !slices.Equal(found, want) { t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want) } - if strings.Contains(strings.Join(found, ","), "Visible") { - t.Fatal("the organization-facing read names the table directly") - } closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"]) for _, required := range []string{ "select greatest(candidate_publications.published_at, consent_records.revoked_at)", @@ -100,7 +101,53 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { t.Errorf("consent revocation query lacks %q: %s", required, closeQuery) } } + settingsQuery := strings.ToLower(statements["ReadCandidatePrivacySettings"]) + for _, required := range []string{ + "users.id = sqlc.arg(user_id)", + "left join candidate_publications", + "left join consent_records", + "left join candidate_search_statuses", + "from candidate_hidden_organizations", + } { + if !strings.Contains(settingsQuery, required) { + t.Errorf("candidate settings query lacks %q: %s", required, settingsQuery) + } + } + for _, forbidden := range []string{"candidate_profiles", "profile_claims", "candidate_questionnaires", "contact_email", "contact_phone"} { + if strings.Contains(settingsQuery, forbidden) { + t.Errorf("candidate settings query reaches private profile data %q: %s", forbidden, settingsQuery) + } + } if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") { t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery) } + previewQuery := strings.ToLower(statements["ReadCandidateViewSourceForPreview"]) + for _, required := range []string{ + "from candidate_effective_publications as effective", + "where effective.user_id = sqlc.arg(candidate_id)", + "claim.kind in ('stack', 'role', 'experience')", + "coalesce(questionnaire.work_formats, '{}'::text[])", + } { + if !strings.Contains(previewQuery, required) { + t.Errorf("owner preview query lacks %q: %s", required, previewQuery) + } + } + visibleLock := strings.ToLower(statements["LockVisiblePublicationForView"]) + for _, required := range []string{ + "candidate_publications.user_id = sqlc.arg(candidate_id)", + "candidate_publications.state = 'published'", + "candidate_publications.consent_record_id = sqlc.arg(consent_record_id)", + "consent_records.purpose = 'c2'", + "consent_records.revoked_at is null", + "candidate_hidden_organizations", + "for share of candidate_publications, consent_records", + } { + if !strings.Contains(visibleLock, required) { + t.Errorf("organization card lock lacks %q: %s", required, visibleLock) + } + } + visibleSource := strings.ToLower(statements["ListVisibleCandidateViewSources"]) + if !effectiveViewName.MatchString(visibleSource) || !hiddenTableName.MatchString(visibleSource) { + t.Errorf("organization cohort source must use the effective publication view and hidden-organization filter: %s", visibleSource) + } } diff --git a/backend/db/queries/assessment_attempts.sql b/backend/db/queries/assessment_attempts.sql new file mode 100644 index 0000000..614335a --- /dev/null +++ b/backend/db/queries/assessment_attempts.sql @@ -0,0 +1,449 @@ +-- 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. +-- name: ResolveCurrentAssessmentSelection :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 = sqlc.arg(specialization) + AND binding.grade = sqlc.arg(grade) + AND ( + (sqlc.narg(task_language)::text IS NULL AND cardinality(binding.task_languages) = 0) + OR sqlc.narg(task_language)::text = ANY(binding.task_languages) + ) +ORDER BY opening.category; + +-- Serializes root quota checks for one candidate before taking its optional +-- specialization or training lock. All callers acquire these locks in order. +-- name: LockAssessmentAttemptScope :exec +WITH candidate_lock AS MATERIALIZED ( + SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:user:' || sqlc.arg(user_id)::text, + 0 + )) +) +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:track:' || sqlc.arg(user_id)::text || ':' || + COALESCE(sqlc.narg(specialization)::text, 'training'), + 0 +)) +FROM candidate_lock; + +-- Locks the active real attempt after LockAssessmentAttemptScope. +-- name: GetActiveAssessmentAttemptForSpecialization :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + 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 +FOR UPDATE; + +-- Locks the one active express attempt after LockAssessmentAttemptScope. +-- name: GetActiveTrainingAssessmentAttempt :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND kind = 'demo_express' + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') +ORDER BY created_at DESC, id DESC +LIMIT 1 +FOR UPDATE; + +-- Reads the latest root in a specialization, optionally restricted to grade. +-- name: GetLatestRootAssessmentAttempt :one +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 +LEFT JOIN assessment_attempt_results AS result + ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id +WHERE attempt.user_id = sqlc.arg(user_id) + AND attempt.specialization = sqlc.arg(specialization) + AND attempt.kind = 'root' + AND (sqlc.narg(target_grade)::text IS NULL OR attempt.target_grade = sqlc.narg(target_grade)::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +ORDER BY attempt.created_at DESC, attempt.id DESC +LIMIT 1 +FOR SHARE OF attempt; + +-- Counts root attempts only; the caller applies the effective policy's +-- configured window and the product's approved accounting scope. +-- name: CountRootAssessmentAttemptsSince :one +SELECT count(*)::bigint +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 = sqlc.arg(user_id) + AND attempt.kind = 'root' + AND attempt.created_at >= sqlc.arg(since)::timestamptz + AND (sqlc.narg(specialization)::text IS NULL OR attempt.specialization = sqlc.narg(specialization)::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable'); + +-- Lists explicit immutable training bindings for the effective product +-- policy. Callers reject more than one matching active binding as ambiguous. +-- name: ListCurrentAssessmentTrainingBindings :many +SELECT + binding.id, + binding.category, + binding.product_policy_version_id, + binding.item_count, + binding.manifest_sha256, + binding.family_manifest, + policy.version AS product_policy_version +FROM assessment_training_bank_bindings AS binding +JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id +WHERE policy.policy_key = 'product' + AND policy.effective_at <= statement_timestamp() + AND NOT EXISTS ( + SELECT 1 FROM policy_versions AS newer + WHERE newer.policy_key = 'product' + AND newer.effective_at <= statement_timestamp() + AND newer.version > policy.version + ) +ORDER BY binding.category, binding.created_at DESC, binding.id; + +-- Reads the exact family membership pinned by a training binding. +-- name: ListAssessmentTrainingBindingFamilies :many +SELECT + family_id, + ordinal, + family_key, + family_version, + content_sha256 +FROM assessment_training_bank_binding_families +WHERE binding_id = sqlc.arg(binding_id) +ORDER BY ordinal; + +-- Inserts the attempt header. The database guard rechecks the current policy, +-- opening or disjoint training binding, and immutable pins. +-- name: InsertAssessmentAttempt :exec +INSERT INTO assessment_attempts ( + id, + user_id, + kind, + mode, + state, + outcome, + bank_category, + specialization, + target_grade, + task_language, + root_attempt_id, + product_policy_version_id, + product_policy_version, + grading_policy_version_id, + opening_id, + opening_manifest_sha256, + training_binding_id, + training_manifest_sha256, + bank_version, + algorithm_version, + created_at, + updated_at, + expires_at, + chain_deadline, + idle_timeout_seconds, + max_sessions, + sessions_used, + session_started_at, + last_activity_at, + version, + ended_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(mode), + sqlc.arg(state), + sqlc.narg(outcome), + sqlc.arg(bank_category), + sqlc.narg(specialization), + sqlc.narg(target_grade), + sqlc.narg(task_language), + sqlc.arg(root_attempt_id), + sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), + sqlc.narg(grading_policy_version_id), + sqlc.narg(opening_id), + sqlc.narg(opening_manifest_sha256), + sqlc.narg(training_binding_id), + sqlc.narg(training_manifest_sha256), + sqlc.arg(bank_version), + sqlc.arg(algorithm_version), + sqlc.arg(created_at), + sqlc.arg(updated_at), + sqlc.arg(expires_at), + sqlc.narg(chain_deadline), + sqlc.arg(idle_timeout_seconds), + sqlc.arg(max_sessions), + sqlc.arg(sessions_used), + sqlc.arg(session_started_at), + sqlc.arg(last_activity_at), + sqlc.arg(version), + sqlc.narg(ended_at) +); + +-- Stores the immutable generated variant and empty answer slot. +-- name: InsertAssessmentAttemptItem :exec +INSERT INTO assessment_attempt_items ( + id, + attempt_id, + ordinal, + family_id, + family_key, + family_version, + family_content_sha256, + variant, + answer, + answered_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(ordinal), + sqlc.arg(family_id), + sqlc.arg(family_key), + sqlc.arg(family_version), + sqlc.arg(family_content_sha256), + sqlc.arg(variant), + sqlc.narg(answer), + sqlc.narg(answered_at) +); + +-- Returns a full private attempt only to its candidate. +-- name: GetAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id) +FOR SHARE; + +-- Reads the immutable attempt kind without locking the row. Session commands +-- use this only to decide whether C3 applies before acquiring the row lock. +-- name: GetAssessmentAttemptKindForCandidate :one +SELECT kind +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id); + +-- Locks one owner-scoped attempt while a session command performs its CAS. +-- name: LockAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id) +FOR UPDATE; + +-- Reads chain headers in creation order. The use case verifies root eligibility +-- and descending target grades in the domain before it creates a correction. +-- name: ListAssessmentAttemptChain :many +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + AND (id = sqlc.arg(root_attempt_id) OR root_attempt_id = sqlc.arg(root_attempt_id)) +ORDER BY created_at, id +FOR SHARE; + +-- Reads private frozen variants and candidate answer bytes in stable order. +-- name: ListAssessmentAttemptItems :many +SELECT + id, attempt_id, ordinal, family_id, family_key, family_version, + family_content_sha256, variant::text AS variant, answer, answered_at +FROM assessment_attempt_items +WHERE attempt_id = sqlc.arg(attempt_id) +ORDER BY ordinal; + +-- Applies a versioned session transition after the attempt row is locked. +-- name: UpdateAssessmentAttemptSession :one +UPDATE assessment_attempts +SET + state = sqlc.arg(state), + outcome = sqlc.narg(outcome), + updated_at = sqlc.arg(updated_at), + sessions_used = sqlc.arg(sessions_used), + session_started_at = sqlc.arg(session_started_at), + last_activity_at = sqlc.arg(last_activity_at), + version = sqlc.arg(version), + ended_at = sqlc.narg(ended_at) +WHERE id = sqlc.arg(id) + AND user_id = sqlc.arg(user_id) + AND version = sqlc.arg(expected_version) +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at; + +-- Stores one final answer before advancing the enclosing attempt version. +-- The caller holds the owner-scoped attempt row lock for the surrounding unit. +-- name: UpdateAssessmentAttemptItemAnswer :one +UPDATE assessment_attempt_items +SET answer = sqlc.arg(answer), answered_at = sqlc.arg(answered_at) +WHERE attempt_id = sqlc.arg(attempt_id) + AND id = sqlc.arg(item_id) + AND answer IS NULL +RETURNING id; + +-- Applies an answer, expiry, or finalization transition after the attempt row +-- is locked. Session limits and all immutable pins remain unchanged. +-- name: UpdateAssessmentAttemptTransition :one +UPDATE assessment_attempts +SET + state = sqlc.arg(state), + outcome = sqlc.narg(outcome), + updated_at = sqlc.arg(updated_at), + last_activity_at = sqlc.arg(last_activity_at), + version = sqlc.arg(version), + ended_at = sqlc.narg(ended_at) +WHERE id = sqlc.arg(id) + AND user_id = sqlc.arg(user_id) + AND version = sqlc.arg(expected_version) +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at; + +-- A newly reserved generic idempotency window can replace an expired typed +-- outcome before the new immutable response is inserted. +-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec +DELETE FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- name: InsertAssessmentAttemptIdempotencyOutcome :exec +INSERT INTO assessment_attempt_idempotency_outcomes ( + scope_hash, operation, status_code, problem_code, response_snapshot, + response_schema_version, pending_item_ids, created_at +) VALUES ( + sqlc.arg(scope_hash), sqlc.arg(operation), sqlc.arg(status_code), + sqlc.narg(problem_code), sqlc.narg(response_snapshot), 1, + sqlc.arg(pending_item_ids)::uuid[], transaction_timestamp() +); + +-- name: GetAssessmentAttemptIdempotencyOutcome :one +SELECT operation, status_code, problem_code, + CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot, + pending_item_ids +FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Stores one immutable candidate-visible result with the decision rationale +-- and source versions used by its finalized attempt. +-- name: InsertAssessmentAttemptResult :exec +INSERT INTO assessment_attempt_results ( + attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome, + product_policy_version_id, product_policy_version, + grading_policy_version_id, opening_id, opening_manifest_sha256, + training_binding_id, training_manifest_sha256, bank_version, algorithm_version, + rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at +) +VALUES ( + sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot)::jsonb, 1, + sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome), + sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version), + sqlc.narg(grading_policy_version_id), sqlc.narg(opening_id), sqlc.narg(opening_manifest_sha256), + sqlc.narg(training_binding_id), sqlc.narg(training_manifest_sha256), + sqlc.arg(bank_version), sqlc.arg(algorithm_version), sqlc.arg(rationale_rule), + sqlc.narg(pass_mark_basis_points), sqlc.narg(scored_items), sqlc.narg(raw_score), + sqlc.narg(pass_points), sqlc.arg(decided_at) +); + +-- Reads a result only for the owning candidate. +-- name: GetAssessmentAttemptResult :one +SELECT result_snapshot::text AS result_snapshot +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id); diff --git a/backend/db/queries/assessment_availability.sql b/backend/db/queries/assessment_availability.sql new file mode 100644 index 0000000..4d774e6 --- /dev/null +++ b/backend/db/queries/assessment_availability.sql @@ -0,0 +1,173 @@ +-- 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. +-- name: ListCurrentAssessmentAvailabilitySelections :many +WITH current_policy AS ( + SELECT id, version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= sqlc.arg(as_of)::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; + +-- Reads an active real attempt without taking the write lock used by create. +-- The availability GET never expires or otherwise mutates this row. +-- name: GetAssessmentAvailabilityActiveAttempt :one +SELECT id, expires_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + 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; + +-- Reads roots within the policy horizon and the last header in each correction +-- chain. It deliberately omits frozen items, answers, and row locks. +-- 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.* + 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 = sqlc.arg(user_id) + AND root.specialization = sqlc.arg(specialization) + AND root.kind = 'root' + AND root.created_at >= sqlc.arg(since)::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; + +-- 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. +-- 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 = sqlc.arg(user_id) + AND attempt.kind = 'root' + AND attempt.state <> 'insufficient_bank' + AND attempt.created_at >= sqlc.arg(since)::timestamptz + AND attempt.created_at <= sqlc.arg(as_of)::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 >= sqlc.arg(max_attempts)::bigint THEN ( + SELECT eligible.created_at + + make_interval(secs => sqlc.arg(window_seconds)::double precision) + + interval '1 microsecond' + FROM eligible + ORDER BY eligible.created_at, eligible.id + LIMIT 1 + OFFSET (total.attempt_count - sqlc.arg(max_attempts)::bigint) + ) ELSE NULL::timestamptz END AS available_at +FROM total; + +-- 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. +-- 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 = sqlc.arg(user_id) + AND attempt.kind IN ('root', 'corrective') + AND attempt.expires_at > sqlc.arg(since)::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 > sqlc.arg(since)::timestamptz +ORDER BY disclosed.family_key; diff --git a/backend/db/queries/assessment_signals.sql b/backend/db/queries/assessment_signals.sql new file mode 100644 index 0000000..60ab7ce --- /dev/null +++ b/backend/db/queries/assessment_signals.sql @@ -0,0 +1,78 @@ +-- New outcomes share the generic idempotency row and are counted for the +-- attempt's rolling receipt window. Replays bypass this query in the usecase. +-- name: CountRecentAssessmentSignalOutcomes :one +SELECT + count(*)::bigint AS outcome_count, + COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at +FROM assessment_signal_idempotency_outcomes +WHERE + attempt_id = sqlc.arg(attempt_id) + AND received_at > sqlc.arg(since); + +-- 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. +-- name: InsertAssessmentSignalBatch :exec +INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) +VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(received_at), + sqlc.arg(event_count) +); + +-- Each inserted event is checked by the database guard against attempt state +-- and the aggregate capacity as a second line of defense. +-- name: InsertAssessmentSignalEvent :exec +INSERT INTO assessment_signal_events ( + batch_id, + attempt_id, + ordinal, + item_instance_id, + kind, + occurred_at, + duration_ms, + size_bytes +) VALUES ( + sqlc.arg(batch_id), + sqlc.arg(attempt_id), + sqlc.arg(ordinal), + sqlc.arg(item_instance_id), + sqlc.arg(kind), + sqlc.arg(occurred_at), + sqlc.narg(duration_ms)::integer, + sqlc.narg(size_bytes)::integer +); + +-- Count events only for the already owner-locked attempt. +-- name: CountAssessmentSignalEvents :one +SELECT count(*)::bigint AS event_count +FROM assessment_signal_events +WHERE attempt_id = sqlc.arg(attempt_id); + +-- The generic reservation has already established that a previous outcome is +-- expired before this child is removed and replaced in the same transaction. +-- name: DeleteExpiredAssessmentSignalOutcome :exec +DELETE FROM assessment_signal_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Save exactly one immutable response receipt for each live idempotency scope. +-- name: InsertAssessmentSignalOutcome :exec +INSERT INTO assessment_signal_idempotency_outcomes ( + scope_hash, + attempt_id, + status, + accepted_events, + received_at +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(attempt_id), + sqlc.arg(status), + sqlc.arg(accepted_events), + sqlc.arg(received_at) +); + +-- Read only the receipt associated with the reserved idempotency scope. +-- name: GetAssessmentSignalOutcome :one +SELECT status, accepted_events, received_at +FROM assessment_signal_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/consents.sql b/backend/db/queries/consents.sql index 976187c..f1beee4 100644 --- a/backend/db/queries/consents.sql +++ b/backend/db/queries/consents.sql @@ -229,6 +229,35 @@ WHERE ORDER BY granted_at DESC, id DESC LIMIT 1; +-- Keeps the current C3 grant stable through a real assessment transaction. +-- Revocation updates this row and therefore waits until the caller commits. +-- 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 = sqlc.arg(subject_id) + AND purpose = 'c3' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +FOR SHARE; + -- Locks the active registration C1 while its pending registration is applied. -- name: LockRegistrationConsentRecord :one SELECT diff --git a/backend/db/queries/needs.sql b/backend/db/queries/needs.sql index 5878ace..261b02d 100644 --- a/backend/db/queries/needs.sql +++ b/backend/db/queries/needs.sql @@ -58,6 +58,34 @@ WHERE AND need_id = sqlc.arg(need_id) AND version = sqlc.arg(version); +-- Read one bounded newest-first page of current needs. Both the organization +-- scope and the tuple cursor are applied before the limit. +-- 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 = sqlc.arg(organization_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (need.created_at, need.id) < ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_need_id)::uuid + ) + ) +ORDER BY need.created_at DESC, need.id DESC +LIMIT sqlc.arg(row_limit); + -- The conditional parent update is the compare-and-swap. Appending the -- snapshot is part of the same SQL statement, so a failed insert leaves the -- parent pointer unchanged even before the surrounding transaction rolls @@ -100,3 +128,19 @@ WITH advanced AS ( ) SELECT appended.snapshot FROM appended; + +-- 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. +-- name: SaveOrganizationNeedCreationResult :exec +INSERT INTO organization_need_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- Read only the immutable original response. The current need may have moved +-- to a later version since this result was created. +-- name: GetOrganizationNeedCreationResult :one +SELECT snapshot::text AS snapshot +FROM organization_need_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/organizations.sql b/backend/db/queries/organizations.sql index f7d9528..e57d365 100644 --- a/backend/db/queries/organizations.sql +++ b/backend/db/queries/organizations.sql @@ -97,6 +97,32 @@ WHERE AND membership.user_id = sqlc.arg(user_id) AND membership.state = 'active'; +-- 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. +-- name: LockActiveMembership :one +WITH locked_organization AS MATERIALIZED ( + SELECT organizations.id + FROM organizations + WHERE organizations.id = sqlc.arg(organization_id) + 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 = sqlc.arg(user_id) + AND membership.state = 'active' +FOR SHARE OF membership; + -- Changes the profile of an organization over the version the caller read -- and advances the version in the same statement. It names no verification -- column, so a profile update cannot move the trust level. The change diff --git a/backend/db/queries/privacy.sql b/backend/db/queries/privacy.sql index 618b522..5fa3159 100644 --- a/backend/db/queries/privacy.sql +++ b/backend/db/queries/privacy.sql @@ -6,6 +6,39 @@ -- 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. +-- 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 = sqlc.arg(user_id); + -- 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 @@ -319,3 +352,74 @@ WHERE hidden.user_id = effective.user_id AND hidden.organization_id = sqlc.arg(organization_id) ); + +-- 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. +-- name: InsertCandidateCardAccessEvent :exec +INSERT INTO candidate_card_access_events ( + id, + candidate_id, + organization_id, + actor_id, + kind, + field_codes, + occurred_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(candidate_id), + sqlc.arg(organization_id), + sqlc.narg(actor_id), + sqlc.arg(kind), + sqlc.arg(field_codes), + sqlc.arg(occurred_at) +); + +-- 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. +-- 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 = sqlc.arg(candidate_id) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC +LIMIT sqlc.arg(row_limit); + +-- 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. +-- name: CandidateCanSeeOrganization :one +SELECT organizations.id, organizations.name +FROM organizations +WHERE organizations.id = sqlc.arg(organization_id) + AND ( + EXISTS ( + SELECT 1 FROM candidate_card_access_events + WHERE candidate_card_access_events.candidate_id = sqlc.arg(user_id) + AND candidate_card_access_events.organization_id = organizations.id + ) + OR EXISTS ( + SELECT 1 FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND candidate_hidden_organizations.organization_id = organizations.id + ) + ); diff --git a/backend/db/queries/privacy_cohort.sql b/backend/db/queries/privacy_cohort.sql new file mode 100644 index 0000000..c0cb5a2 --- /dev/null +++ b/backend/db/queries/privacy_cohort.sql @@ -0,0 +1,181 @@ +-- 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. +-- 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 = sqlc.arg(organization_id) +) +ORDER BY effective.user_id, claim.kind, claim.ordinal; + +-- 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. +-- name: LockCandidateAccountForView :one +SELECT users.id +FROM users +WHERE users.id = sqlc.arg(candidate_id) +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. +-- name: LockCurrentC2ForView :one +SELECT consent_records.id +FROM consent_records +WHERE + consent_records.subject_id = sqlc.arg(candidate_id) + 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 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. +-- 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 = sqlc.arg(candidate_id) + AND candidate_publications.state = 'published' + AND candidate_publications.consent_record_id = sqlc.arg(consent_record_id) + 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 = sqlc.arg(organization_id) + ) +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. +-- 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 = sqlc.arg(candidate_id) + 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; + +-- 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. +-- 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 = sqlc.arg(candidate_id) +ORDER BY effective.user_id, claim.kind, claim.ordinal; diff --git a/backend/db/queries/support_cases.sql b/backend/db/queries/support_cases.sql new file mode 100644 index 0000000..b1c8f6b --- /dev/null +++ b/backend/db/queries/support_cases.sql @@ -0,0 +1,154 @@ +-- Case numbers are monotonic and never reused. Sequence gaps on a rolled-back +-- request are expected and do not expose request contents. +-- name: NextSupportCaseNumber :one +WITH next_value AS MATERIALIZED ( + SELECT nextval('support_case_number_seq') AS value +) +SELECT + 'SC-' || sqlc.arg(utc_year)::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; + +-- 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. +-- 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 ( + sqlc.arg(id), sqlc.arg(case_number), sqlc.arg(owner_id), sqlc.arg(case_type), + sqlc.arg(status), sqlc.arg(description), sqlc.narg(object_type), sqlc.narg(object_id), + sqlc.narg(assessment_specialization), sqlc.narg(assessment_grade), + sqlc.narg(complaint_reason), sqlc.narg(rubric_version), sqlc.narg(rubric_opening_id), + sqlc.narg(rubric_policy_version_id), sqlc.arg(target_business_days), + sqlc.arg(target_due_at), sqlc.narg(target_answered_at), sqlc.arg(target_policy_version), + sqlc.arg(target_calendar_version), sqlc.narg(decision_outcome), sqlc.narg(decision_reason), + sqlc.narg(decision_at), sqlc.arg(created_at), sqlc.arg(updated_at) +) +ON CONFLICT DO NOTHING; + +-- name: InsertSupportCaseEvent :exec +INSERT INTO support_case_events ( + case_id, sequence, event_kind, actor_kind, occurred_at, status, message +) VALUES ( + sqlc.arg(case_id), sqlc.arg(sequence), sqlc.arg(event_kind), sqlc.arg(actor_kind), + sqlc.arg(occurred_at), sqlc.narg(status), sqlc.narg(message) +); + +-- Reads a full owner-scoped record. Object values are identifiers only. +-- 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 = sqlc.arg(case_id) AND owner_id = sqlc.arg(owner_id); + +-- Reads the immutable public history only after the case owner has matched. +-- name: ReadSupportCaseEvents :many +SELECT sequence, event_kind, actor_kind, occurred_at, status, message +FROM support_case_events +WHERE case_id = sqlc.arg(case_id) +ORDER BY sequence; + +-- Owner-scoped newest-first list. It omits descriptions, complaint reason, +-- and event history. The tuple cursor matches the composite sort key. +-- name: ListOwnedSupportCases :many +WITH cursor_input AS MATERIALIZED ( + SELECT + sqlc.narg(after_created_at)::timestamptz AS after_created_at, + sqlc.narg(after_id)::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 = sqlc.arg(owner_id) + 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 sqlc.arg(row_limit); + +-- No raw Idempotency-Key or request body reaches these statements. Failure +-- responses pass {} as case_snapshot and the CASE stores SQL NULL instead. +-- name: DeleteSupportCaseCreateOutcome :exec +DELETE FROM support_case_create_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- name: InsertSupportCaseCreateOutcome :exec +INSERT INTO support_case_create_outcomes ( + scope_hash, outcome_kind, case_snapshot, target_was_late, created_at +) VALUES ( + sqlc.arg(scope_hash), sqlc.arg(outcome_kind), + CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(case_snapshot)::jsonb END, + CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(target_was_late)::boolean END, + sqlc.arg(created_at) +); + +-- name: ReadSupportCaseCreateOutcome :one +SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late +FROM support_case_create_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Serialize per-owner budget checks even before the first event exists. +-- name: LockSupportCaseRequestBudget :exec +SELECT pg_advisory_xact_lock( + hashtextextended('lincodex.support.case.requests:' || sqlc.arg(owner_id)::uuid::text, 0) +); + +-- Read the latest serialized event so a temporarily regressing application +-- clock cannot make the next request fall before an event already counted. +-- name: LatestSupportCaseRequestEvent :one +SELECT requested_at +FROM support_case_request_events +WHERE owner_id = sqlc.arg(owner_id) +ORDER BY requested_at DESC, id DESC +LIMIT 1; + +-- Keep up to the maximum supported window, regardless of the current policy. +-- The bounded delete prevents one create from doing unbounded cleanup work. +-- name: PruneSupportCaseRequestEvents :execrows +WITH expired AS MATERIALIZED ( + SELECT source.id + FROM support_case_request_events AS source + WHERE source.owner_id = sqlc.arg(owner_id) + AND source.requested_at <= sqlc.arg(at)::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; + +-- The strict lower boundary means an event exactly one window old no longer +-- counts. The use case derives Retry-After from first_in_window. +-- name: CountSupportCaseRequestEvents :one +SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window +FROM support_case_request_events +WHERE owner_id = sqlc.arg(owner_id) + AND requested_at > sqlc.arg(window_start)::timestamptz + AND requested_at <= sqlc.arg(at)::timestamptz; + +-- name: InsertSupportCaseRequestEvent :exec +INSERT INTO support_case_request_events (owner_id, requested_at) +VALUES (sqlc.arg(owner_id), sqlc.arg(requested_at)); diff --git a/backend/db/queries/support_rubrics.sql b/backend/db/queries/support_rubrics.sql new file mode 100644 index 0000000..799e6d1 --- /dev/null +++ b/backend/db/queries/support_rubrics.sql @@ -0,0 +1,53 @@ +-- 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. +-- 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 = sqlc.arg(specialization) + AND binding.grade = sqlc.arg(grade) +ORDER BY opening.category; diff --git a/backend/integration_test/assessment_answer_http_test.go b/backend/integration_test/assessment_answer_http_test.go new file mode 100644 index 0000000..a771d5b --- /dev/null +++ b/backend/integration_test/assessment_answer_http_test.go @@ -0,0 +1,461 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/domain" +) + +func TestAssessmentAnswerAndResultPersistAcrossRouterReconstruction(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "answer-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234") + + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, + "answer-flow-create", "203.0.113.43:1234") + if create.Code != http.StatusCreated { + t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String()) + } + var publicAttempt assessmentAnswerHTTPAttempt + if err := json.Unmarshal(create.Body.Bytes(), &publicAttempt); err != nil || publicAttempt.ID == uuid.Nil || publicAttempt.CurrentItem == nil { + t.Fatalf("created attempt = %+v, decode error %v", publicAttempt, err) + } + items := readAssessmentAnswerHTTPItems(t, ctx, harness, publicAttempt.ID) + if len(items) < 2 || items[0].ID != publicAttempt.CurrentItem.ID { + t.Fatalf("frozen item count/current item = %d/%s, want ordered item list starting at current item", len(items), publicAttempt.CurrentItem.ID) + } + + finalizePath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + "/finalize" + finalizeBody, err := json.Marshal(map[string]int64{"expected_version": publicAttempt.Version}) + if err != nil { + t.Fatalf("marshal early finalize: %v", err) + } + earlyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234") + var pendingProblem struct { + Code string `json:"code"` + PendingItemIDs []uuid.UUID `json:"pending_item_ids"` + } + if earlyFinalize.Code != http.StatusConflict || json.Unmarshal(earlyFinalize.Body.Bytes(), &pendingProblem) != nil || + pendingProblem.Code != "state_conflict" || len(pendingProblem.PendingItemIDs) != len(items) { + t.Fatalf("early finalize = %d %s, want state_conflict with %d pending item IDs", earlyFinalize.Code, earlyFinalize.Body.String(), len(items)) + } + for index, item := range items { + if pendingProblem.PendingItemIDs[index] != item.ID { + t.Fatalf("pending item %d = %s, want frozen item %s", index, pendingProblem.PendingItemIDs[index], item.ID) + } + } + finalizeReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234") + if finalizeReplay.Code != earlyFinalize.Code || + assessmentHTTPBodyWithoutTraceID(t, finalizeReplay.Body.String()) != assessmentHTTPBodyWithoutTraceID(t, earlyFinalize.Body.String()) { + t.Fatalf("early finalize replay = %d %s, want stored %d %s", finalizeReplay.Code, finalizeReplay.Body.String(), earlyFinalize.Code, earlyFinalize.Body.String()) + } + + firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, publicAttempt.Version, items[0], false) + withClientScore := strings.TrimSuffix(string(firstAnswer), "}") + `,"score":100}` + clientScore := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", withClientScore, + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + if clientScore.Code != http.StatusBadRequest { + t.Fatalf("answer with client score = %d %s, want rejected request", clientScore.Code, clientScore.Body.String()) + } + answerScope := harness.keyring.IdempotencyScope("assessment_attempt.answer", "answer-flow-first", candidate.ID.String()) + var badScoreOutcomeCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash=$1", answerScope[:]).Scan(&badScoreOutcomeCount); err != nil || badScoreOutcomeCount != 0 { + t.Fatalf("invalid client score reserved idempotency row count=%d error=%v, want zero", badScoreOutcomeCount, err) + } + + firstAccepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + var firstSnapshot assessmentAnswerHTTPAttempt + if firstAccepted.Code != http.StatusOK || json.Unmarshal(firstAccepted.Body.Bytes(), &firstSnapshot) != nil || + firstSnapshot.Version != publicAttempt.Version+1 || firstSnapshot.CurrentItem == nil || firstSnapshot.CurrentItem.ID != items[1].ID { + t.Fatalf("first answer = %d %s, want next frozen item and incremented version", firstAccepted.Code, firstAccepted.Body.String()) + } + storedAnswer, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID) + if len(storedAnswer) == 0 || answeredAt.IsZero() { + t.Fatalf("first answer storage = bytes %d, answered_at %s; want canonical answer and server time", len(storedAnswer), answeredAt) + } + answerReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + if answerReplay.Code != firstAccepted.Code || answerReplay.Body.String() != firstAccepted.Body.String() { + t.Fatalf("answer replay = %d %s, want stored %d %s", answerReplay.Code, answerReplay.Body.String(), firstAccepted.Code, firstAccepted.Body.String()) + } + + // A reconstructed service graph and router read the committed answer and + // its server timestamp from PostgreSQL, not the old handler's memory. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + readPath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + reconstructedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, readPath, "", "", + cookie.Value, "", "", "203.0.113.46:1234") + var reconstructedAttempt assessmentAnswerHTTPAttempt + if reconstructedRead.Code != http.StatusOK || json.Unmarshal(reconstructedRead.Body.Bytes(), &reconstructedAttempt) != nil || + reconstructedAttempt.Version != firstSnapshot.Version || reconstructedAttempt.CurrentItem == nil || + reconstructedAttempt.CurrentItem.ID != firstSnapshot.CurrentItem.ID { + t.Fatalf("GET after router reconstruction = %d %s, want version %d and item %s", reconstructedRead.Code, reconstructedRead.Body.String(), firstSnapshot.Version, firstSnapshot.CurrentItem.ID) + } + reconstructedAnswer, reconstructedAnsweredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID) + if string(reconstructedAnswer) != string(storedAnswer) || !reconstructedAnsweredAt.Equal(answeredAt) { + t.Fatalf("answer after router reconstruction differs: bytes equal=%v timestamp=%s want %s", string(reconstructedAnswer) == string(storedAnswer), reconstructedAnsweredAt, answeredAt) + } + + currentVersion := reconstructedAttempt.Version + for _, item := range items[1:] { + body := assessmentAnswerHTTPBody(t, currentVersion, item) + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-item-%d", item.Ordinal), + fmt.Sprintf("203.0.113.%d:1234", 50+item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != currentVersion+1 { + t.Fatalf("answer frozen item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), currentVersion+1) + } + if item.Ordinal < int32(len(items)) && (next.CurrentItem == nil || next.CurrentItem.ID != items[item.Ordinal].ID) { + t.Fatalf("answer item %d returned current item %+v, want %s", item.Ordinal, next.CurrentItem, items[item.Ordinal].ID) + } + if item.Ordinal == int32(len(items)) && (next.State != "ready_to_finalize" || next.CurrentItem != nil) { + t.Fatalf("final answer returned state=%s current_item=%+v, want ready_to_finalize", next.State, next.CurrentItem) + } + currentVersion = next.Version + } + + finalizeBody, err = json.Marshal(map[string]int64{"expected_version": currentVersion}) + if err != nil { + t.Fatalf("marshal finalization: %v", err) + } + finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.90:1234") + var completed assessmentAnswerHTTPAttempt + if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" { + t.Fatalf("finalize complete attempt = %d %s, want completed", finalized.Code, finalized.Body.String()) + } + resultPath := readPath + "/result" + resultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "", + cookie.Value, "", "", "203.0.113.91:1234") + var realResult map[string]any + if resultResponse.Code != http.StatusOK || json.Unmarshal(resultResponse.Body.Bytes(), &realResult) != nil || + realResult["attempt_id"] != publicAttempt.ID.String() || realResult["outcome"] != "confirmed" { + t.Fatalf("read completed result = %d %s, want persisted confirmed result", resultResponse.Code, resultResponse.Body.String()) + } + score, ok := realResult["basic_score"].(map[string]any) + points, pointsOK := score["points"].(float64) + maxPoints, maxPointsOK := score["max_points"].(float64) + if !ok || !pointsOK || !maxPointsOK || points != maxPoints-1 || score["pass_points"] == nil { + t.Fatalf("real result basic score = %#v, want one incorrect server-scored item", realResult["basic_score"]) + } + sameKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.94:1234") + if sameKeyFinalize.Code != finalized.Code || sameKeyFinalize.Body.String() != finalized.Body.String() { + t.Fatalf("completed finalize replay = %d %s, want stored %d %s", sameKeyFinalize.Code, sameKeyFinalize.Body.String(), finalized.Code, finalized.Body.String()) + } + newFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": completed.Version}) + if err != nil { + t.Fatalf("marshal completed finalize retry: %v", err) + } + newKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(newFinalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize-again", "203.0.113.95:1234") + if newKeyFinalize.Code != finalized.Code || newKeyFinalize.Body.String() != finalized.Body.String() { + t.Fatalf("new-key completed finalize = %d %s, want existing terminal projection %d %s", newKeyFinalize.Code, newKeyFinalize.Body.String(), finalized.Code, finalized.Body.String()) + } + var resultRowCount int64 + var persistedVersion int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempt_results WHERE attempt_id=$1", publicAttempt.ID).Scan(&resultRowCount); err != nil { + t.Fatalf("count immutable result rows: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT version FROM assessment_attempts WHERE id=$1", publicAttempt.ID).Scan(&persistedVersion); err != nil { + t.Fatalf("read finalized attempt version: %v", err) + } + if resultRowCount != 1 || persistedVersion != completed.Version { + t.Fatalf("finalize retries left %d result rows and version %d, want one row and version %d", resultRowCount, persistedVersion, completed.Version) + } + resultSnapshot, productPolicyID, openingID, rawScore, passMark, rawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, publicAttempt.ID) + if resultSnapshot["outcome"] != "confirmed" || !rawScoreValid || rawScore != int16(score["points"].(float64)) { + t.Fatalf("stored result outcome/score = %v/%d (valid %v), API result = %v/%v", resultSnapshot["outcome"], rawScore, rawScoreValid, realResult["outcome"], score["points"]) + } + pins, ok := resultSnapshot["pins"].(map[string]any) + if !ok || pins["product_policy_version_id"] != productPolicyID.String() || pins["opening_id"] != openingID.String() || + !strings.Contains(stringMustJSON(t, resultSnapshot), `"product_policy_version_id":"`+productPolicyID.String()+`"`) { + t.Fatalf("stored result pin IDs are not UUID strings: %#v", resultSnapshot["pins"]) + } + if passMark < 1 || strings.Contains(resultResponse.Body.String(), "ReferenceAnswer") || strings.Contains(resultResponse.Body.String(), "answer_key") { + t.Fatalf("result exposed private source or lost its stored pass mark: body=%s pass_mark=%d", resultResponse.Body.String(), passMark) + } + + // The result projection is read from the immutable stored snapshot after a + // second router/pool reconstruction and stays byte-for-byte stable. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + restartedResult := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "", + cookie.Value, "", "", "203.0.113.92:1234") + if restartedResult.Code != http.StatusOK || restartedResult.Body.String() != resultResponse.Body.String() { + t.Fatalf("result after router reconstruction = %d %s, want stored projection %s", restartedResult.Code, restartedResult.Body.String(), resultResponse.Body.String()) + } + + var rootAttemptsBeforeExpress int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsBeforeExpress); err != nil { + t.Fatalf("count real attempts before express completion: %v", err) + } + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-create", "203.0.113.93:1234") + var training assessmentAnswerHTTPAttempt + if trainingCreate.Code != http.StatusCreated || json.Unmarshal(trainingCreate.Body.Bytes(), &training) != nil || training.ID == uuid.Nil { + t.Fatalf("create express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + trainingItems := readAssessmentAnswerHTTPItems(t, ctx, harness, training.ID) + trainingVersion := training.Version + for _, item := range trainingItems { + body := assessmentAnswerHTTPBody(t, trainingVersion, item) + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-express-%d", item.Ordinal), + fmt.Sprintf("203.0.113.%d:1234", 100+item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != trainingVersion+1 { + t.Fatalf("answer express item %d = %d %s", item.Ordinal, response.Code, response.Body.String()) + } + trainingVersion = next.Version + } + trainingFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": trainingVersion}) + if err != nil { + t.Fatalf("marshal express finalization: %v", err) + } + trainingFinalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/finalize", string(trainingFinalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-finalize", "203.0.113.110:1234") + if trainingFinalized.Code != http.StatusOK { + t.Fatalf("finalize express attempt = %d %s", trainingFinalized.Code, trainingFinalized.Body.String()) + } + trainingResultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/result", "", "", cookie.Value, "", "", "203.0.113.111:1234") + var trainingResult map[string]any + if trainingResultResponse.Code != http.StatusOK || json.Unmarshal(trainingResultResponse.Body.Bytes(), &trainingResult) != nil || + trainingResult["outcome"] != "demonstration" || trainingResult["mode"] != "demo_express" || + trainingResult["basic_score"] != nil || trainingResult["confirmed_grade"] != nil || trainingResult["specialization"] != nil { + t.Fatalf("express result = %d %s, want demonstration without score or grade", trainingResultResponse.Code, trainingResultResponse.Body.String()) + } + _, _, _, expressRawScore, _, expressRawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, training.ID) + if expressRawScoreValid { + t.Fatalf("express result stored raw score %d, want SQL NULL", expressRawScore) + } + var rootAttemptsAfterExpress int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsAfterExpress); err != nil { + t.Fatalf("count real attempts after express completion: %v", err) + } + if rootAttemptsAfterExpress != rootAttemptsBeforeExpress { + t.Fatalf("express completion changed real root quota count from %d to %d", rootAttemptsBeforeExpress, rootAttemptsAfterExpress) + } +} + +type assessmentAnswerHTTPAttempt struct { + ID uuid.UUID `json:"id"` + Version int64 `json:"version"` + State string `json:"state"` + CurrentItem *struct { + ID uuid.UUID `json:"id"` + } `json:"current_item"` +} + +type assessmentAnswerHTTPItem struct { + ID uuid.UUID + Ordinal int32 + Variant domain.AssessmentVariant +} + +func readAssessmentAnswerHTTPItems( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, +) []assessmentAnswerHTTPItem { + t.Helper() + rows, err := harness.pool.Query(ctx, `SELECT id, ordinal, variant FROM assessment_attempt_items WHERE attempt_id=$1 ORDER BY ordinal`, attemptID) + if err != nil { + t.Fatalf("read frozen assessment items: %v", err) + } + defer rows.Close() + items := make([]assessmentAnswerHTTPItem, 0) + for rows.Next() { + var item assessmentAnswerHTTPItem + var encoded []byte + if err := rows.Scan(&item.ID, &item.Ordinal, &encoded); err != nil { + t.Fatalf("scan frozen assessment item: %v", err) + } + item.Variant, err = domain.UnmarshalAssessmentAttemptVariant(encoded) + if err != nil { + t.Fatalf("restore frozen assessment variant: %v", err) + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + t.Fatalf("iterate frozen assessment items: %v", err) + } + return items +} + +func readAssessmentAnswerHTTPItem( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID, itemID uuid.UUID, +) ([]byte, time.Time) { + t.Helper() + var answer []byte + var answeredAt time.Time + if err := harness.pool.QueryRow(ctx, `SELECT answer, answered_at FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2`, + attemptID, itemID).Scan(&answer, &answeredAt); err != nil { + t.Fatalf("read stored answer and server time: %v", err) + } + return answer, answeredAt.UTC() +} + +func assessmentAnswerHTTPBody(t *testing.T, version int64, item assessmentAnswerHTTPItem) []byte { + return assessmentAnswerHTTPBodyWithCorrectness(t, version, item, true) +} + +func assessmentAnswerHTTPBodyWithCorrectness( + t *testing.T, + version int64, + item assessmentAnswerHTTPItem, + wantCorrect bool, +) []byte { + t.Helper() + var answer []byte + switch item.Variant.AnswerFormat { + case domain.AnswerFormatInteger: + reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64) + if err != nil { + t.Fatalf("parse frozen answer key %q: %v", item.Variant.ReferenceAnswer, err) + } + if !wantCorrect { + reference++ + } + answer = []byte(fmt.Sprintf(`{"format":"number","number":%d}`, reference)) + case domain.AnswerFormatIntegerSequence: + parts := strings.Fields(item.Variant.ReferenceAnswer) + if !wantCorrect && len(parts) < 2 { + t.Fatalf("frozen sequence answer %q has fewer than two tasks", item.Variant.ReferenceAnswer) + } + elements := make([]string, 0, len(parts)) + for _, part := range parts { + elements = append(elements, "job_"+part) + } + if !wantCorrect { + elements[0], elements[1] = elements[1], elements[0] + } + var err error + answer, err = json.Marshal(struct { + Format string `json:"format"` + ElementIDs []string `json:"element_ids"` + }{Format: "order", ElementIDs: elements}) + if err != nil { + t.Fatalf("marshal order answer: %v", err) + } + default: + t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat) + } + _, correct, err := domain.CanonicalAssessmentAnswerForVariant(answer, item.Variant) + if err != nil || correct != wantCorrect { + t.Fatalf("fixture answer for item %s has correctness %v, want %v: error %v", item.ID, correct, wantCorrect, err) + } + body, err := json.Marshal(struct { + ExpectedVersion int64 `json:"expected_version"` + ItemID uuid.UUID `json:"item_id"` + Answer json.RawMessage `json:"answer"` + }{ExpectedVersion: version, ItemID: item.ID, Answer: answer}) + if err != nil { + t.Fatalf("marshal answer command: %v", err) + } + return body +} + +func readAssessmentAttemptHTTPResult( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, +) (map[string]any, uuid.UUID, uuid.UUID, int16, int32, bool) { + t.Helper() + var encoded []byte + var productPolicyID uuid.UUID + var storedOpeningID pgtype.UUID + var rawScore pgtype.Int2 + var passMark pgtype.Int4 + if err := harness.pool.QueryRow(ctx, ` + SELECT result_snapshot, product_policy_version_id, opening_id, raw_score, pass_mark_basis_points + FROM assessment_attempt_results WHERE attempt_id=$1`, attemptID). + Scan(&encoded, &productPolicyID, &storedOpeningID, &rawScore, &passMark); err != nil { + t.Fatalf("read immutable assessment result row: %v", err) + } + var openingID uuid.UUID + if storedOpeningID.Valid { + openingID = uuid.UUID(storedOpeningID.Bytes) + } + var document map[string]any + if err := json.Unmarshal(encoded, &document); err != nil { + t.Fatalf("decode immutable assessment result document: %v", err) + } + if !rawScore.Valid || !passMark.Valid { + return document, productPolicyID, openingID, 0, 0, rawScore.Valid + } + return document, productPolicyID, openingID, rawScore.Int16, passMark.Int32, rawScore.Valid +} + +func stringMustJSON(t *testing.T, value any) string { + t.Helper() + encoded, err := json.Marshal(value) + if err != nil { + t.Fatalf("marshal result snapshot for assertion: %v", err) + } + return string(encoded) +} + +func assessmentHTTPBodyWithoutTraceID(t *testing.T, body string) string { + t.Helper() + var document map[string]json.RawMessage + if err := json.Unmarshal([]byte(body), &document); err != nil { + t.Fatalf("decode HTTP problem response: %v", err) + } + delete(document, "trace_id") + encoded, err := json.Marshal(document) + if err != nil { + t.Fatalf("marshal HTTP problem response: %v", err) + } + return string(encoded) +} diff --git a/backend/integration_test/assessment_attempt_http_test.go b/backend/integration_test/assessment_attempt_http_test.go new file mode 100644 index 0000000..bf9f999 --- /dev/null +++ b/backend/integration_test/assessment_attempt_http_test.go @@ -0,0 +1,1025 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" + questionnaireusecase "lincodex/backend/internal/usecase/questionnaire" +) + +const assessmentAttemptHTTPTimeout = 6 * time.Minute + +func TestAssessmentAttemptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + registeredAt := harness.clock.Now() + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-owner@example.test", passwordHash, true) + missingConsent := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-no-consent@example.test", passwordHash, true) + otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-other@example.test", passwordHash, true) + employer := createQuestionnaireHTTPEmployer(ctx, t, harness.sessionHTTPHarness, "attempt-employer@example.test", passwordHash, registeredAt) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = ANY($1)", + []uuid.UUID{candidate.ID, missingConsent.ID, otherCandidate.ID}); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.241:1234") + missingCookie, missingCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, missingConsent.Email.Address(), "192.0.2.242:1234") + otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.243:1234") + employerCookie, employerCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.244:1234") + + backendBody := assessmentAttemptCreateBody(t, "backend") + guestCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, "", "", "guest-create", "192.0.2.245:1234") + requireSessionProblem(t, guestCreate, http.StatusUnauthorized, "unauthenticated") + employerCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, employerCookie.Value, employerCSRF, "employer-create", "192.0.2.246:1234") + requireSessionProblem(t, employerCreate, http.StatusForbidden, "forbidden") + missingC3Create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, missingCookie.Value, missingCSRF, "missing-c3-create", "192.0.2.247:1234") + requireSessionProblem(t, missingC3Create, http.StatusForbidden, "forbidden") + assertAttemptCount(t, ctx, harness.pool, 0) + + if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "192.0.2.248:1234"); response.Code != http.StatusOK { + t.Fatalf("save two-specialization questionnaire = %d %s", response.Code, response.Body.String()) + } + trainingBody := `{"kind":"demo_express"}` + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "192.0.2.248:1235") + if trainingCreate.Code != http.StatusCreated { + t.Fatalf("create reviewed express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + var trainingSnapshot struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Mode string `json:"mode"` + State string `json:"state"` + } + if err := json.Unmarshal(trainingCreate.Body.Bytes(), &trainingSnapshot); err != nil || trainingSnapshot.ID == uuid.Nil || + trainingSnapshot.Kind != "demo_express" || trainingSnapshot.Mode != "demo_express" || trainingSnapshot.State != "in_progress" { + t.Fatalf("express attempt = %+v, decode error %v", trainingSnapshot, err) + } + assertAttemptCount(t, ctx, harness.pool, 1) + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.249:1234") + + // Both requests pass the same candidate-wide root quota through different + // specialization locks. Exactly one can reserve the only root slot. + requests := []struct { + key string + body string + addr string + }{ + {key: "attempt-backend-root", body: backendBody, addr: "192.0.2.250:1234"}, + {key: "attempt-frontend-root", body: assessmentAttemptCreateBody(t, "frontend"), addr: "192.0.2.251:1234"}, + } + responses := make([]*httptest.ResponseRecorder, len(requests)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index := range requests { + wait.Add(1) + go func(index int) { + defer wait.Done() + <-start + request := requests[index] + responses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", request.body, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr) + }(index) + } + close(start) + wait.Wait() + + accepted := -1 + conflicted := -1 + for index, response := range responses { + switch response.Code { + case http.StatusCreated: + accepted = index + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("created attempt Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + case http.StatusConflict: + requireSessionProblem(t, response, http.StatusConflict, "state_conflict") + conflicted = index + default: + t.Fatalf("concurrent create %s = %d %s, want one 201 and one 409", requests[index].key, response.Code, response.Body.String()) + } + } + if accepted < 0 || conflicted < 0 || accepted == conflicted { + t.Fatalf("concurrent root results accepted=%d conflicted=%d, want one of each", accepted, conflicted) + } + for index, response := range responses { + replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", requests[index].body, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[index].key, requests[index].addr) + assertAssessmentAttemptReplay(t, requests[index].key, response, replay) + } + var acceptedAttempt struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Version int64 `json:"version"` + State string `json:"state"` + Specialization string `json:"specialization"` + } + if err := json.Unmarshal(responses[accepted].Body.Bytes(), &acceptedAttempt); err != nil || acceptedAttempt.ID == uuid.Nil || + acceptedAttempt.Kind != "root" || acceptedAttempt.Version != 1 || acceptedAttempt.State != "in_progress" { + t.Fatalf("created attempt = %+v, decode error %v", acceptedAttempt, err) + } + for _, privateField := range []string{`"answer_key"`, `"family_id"`, `"family_key"`, `"variant"`, `"variant_seed"`, `"solution"`} { + if strings.Contains(responses[accepted].Body.String(), privateField) { + t.Fatalf("public attempt response exposed %s", privateField) + } + } + assertAttemptCount(t, ctx, harness.pool, 2) + changedBody := assessmentAttemptCreateBody(t, "frontend") + if requests[accepted].body == changedBody { + changedBody = assessmentAttemptCreateBodyWithGrade(t, "backend", "middle") + } + keyReuse := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", changedBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[accepted].key, "192.0.2.252:1234") + requireSessionProblem(t, keyReuse, http.StatusUnprocessableEntity, "idempotency_key_reused") + assertAttemptCount(t, ctx, harness.pool, 2) + + getPath := "/api/v1/me/assessment-attempts/" + acceptedAttempt.ID.String() + before := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID) + for range 2 { + read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "192.0.2.253:1234") + if read.Code != http.StatusOK || read.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("own attempt read = %d Cache-Control=%q: %s", read.Code, read.Header().Get("Cache-Control"), read.Body.String()) + } + if read.Body.String() != responses[accepted].Body.String() { + t.Fatalf("GET attempt projection differs from immutable create result: got %s want %s", read.Body.String(), responses[accepted].Body.String()) + } + } + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("read-only GET changed attempt state: before=%+v after=%+v", before, after) + } + var createdProjection struct { + CurrentItem *struct { + ID uuid.UUID `json:"id"` + Prompt string `json:"prompt"` + } `json:"current_item"` + } + if err := json.Unmarshal(responses[accepted].Body.Bytes(), &createdProjection); err != nil || createdProjection.CurrentItem == nil || + createdProjection.CurrentItem.ID == uuid.Nil || createdProjection.CurrentItem.Prompt == "" { + t.Fatalf("decode created public item = %+v, error %v", createdProjection, err) + } + // A new pool, service graph, and router must read the same frozen item from + // PostgreSQL after reconstruction, not merely reuse an in-memory handler. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + restartedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "198.51.100.0:1234") + var restartedProjection struct { + CurrentItem *struct { + ID uuid.UUID `json:"id"` + Prompt string `json:"prompt"` + } `json:"current_item"` + } + if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restartedProjection) != nil || + restartedProjection.CurrentItem == nil || restartedProjection.CurrentItem.ID != createdProjection.CurrentItem.ID || + restartedProjection.CurrentItem.Prompt != createdProjection.CurrentItem.Prompt || + restartedRead.Body.String() != responses[accepted].Body.String() { + t.Fatalf("GET after router reconstruction = %d %s, want item %s and original text", restartedRead.Code, restartedRead.Body.String(), createdProjection.CurrentItem.ID) + } + foreignRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", otherCookie.Value, "", "", "192.0.2.254:1234") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + unknownRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+uuid.NewString(), "", "", candidateCookie.Value, "", "", "192.0.2.255:1234") + requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found") + employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", employerCookie.Value, "", "", "198.51.100.1:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + guestRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", "", "", "", "198.51.100.2:1234") + requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated") + + // Revocation wins before a session command and leaves both the attempt and + // its session budget unchanged. Restoring C3 permits the same key to run. + revokeC3 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin, + candidateCookie.Value, candidateCSRF, "198.51.100.3:1234") + if revokeC3.Code != http.StatusNoContent { + t.Fatalf("revoke C3 before session = %d %s", revokeC3.Code, revokeC3.Body.String()) + } + sessionPath := getPath + "/sessions" + sessionBody := `{"expected_version":1}` + blockedSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-session-key", "198.51.100.4:1234") + requireSessionProblem(t, blockedSession, http.StatusForbidden, "forbidden") + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("C3-denied session command changed attempt: before=%+v after=%+v", before, after) + } + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.260:1234") + startRequests := []struct { + key string + addr string + }{ + {key: "attempt-session-key", addr: "198.51.100.5:1234"}, + {key: "attempt-session-key-two", addr: "198.51.100.6:1234"}, + } + startResponses := make([]*httptest.ResponseRecorder, len(startRequests)) + startGate := make(chan struct{}) + var startWait sync.WaitGroup + for index := range startRequests { + startWait.Add(1) + go func(index int) { + defer startWait.Done() + <-startGate + request := startRequests[index] + startResponses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr) + }(index) + } + close(startGate) + startWait.Wait() + started := startResponses[0] + for index, response := range startResponses { + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("concurrent session start %s = %d Cache-Control=%q: %s", startRequests[index].key, response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + if response.Body.String() != started.Body.String() { + t.Fatalf("concurrent session starts returned different snapshots: %s != %s", response.Body.String(), started.Body.String()) + } + } + startedReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, startRequests[0].key, startRequests[0].addr) + if startedReplay.Code != started.Code || startedReplay.Body.String() != started.Body.String() { + t.Fatalf("session replay = %d %s, want stored %d %s", startedReplay.Code, startedReplay.Body.String(), started.Code, started.Body.String()) + } + var sessionSnapshot struct { + Version int64 `json:"version"` + Sessions struct { + Used int32 `json:"used"` + } `json:"sessions"` + } + if err := json.Unmarshal(started.Body.Bytes(), &sessionSnapshot); err != nil || sessionSnapshot.Version != 1 || sessionSnapshot.Sessions.Used != 1 { + t.Fatalf("same-active-session response = %+v, decode error %v; want version 1 and session 1", sessionSnapshot, err) + } + staleSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, `{"expected_version":2}`, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-stale-session", "198.51.100.7:1234") + requireSessionProblem(t, staleSession, http.StatusPreconditionFailed, "version_conflict") + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("stale session command changed attempt: before=%+v after=%+v", before, after) + } + + // The root owns a fixed 72-hour correction window. A terminal failed root + // can create one lower-grade correction without consuming another root + // quota slot, and the child keeps the root's exact deadline. + rootStartedAt, rootDeadline := readAttemptChainTiming(t, ctx, harness.pool, acceptedAttempt.ID) + if rootDeadline.Sub(rootStartedAt) != 72*time.Hour { + t.Fatalf("root chain deadline = %s, database started_at=%s; want 72 hours", rootDeadline, rootStartedAt) + } + terminalizeAttempt(t, ctx, harness.pool, acceptedAttempt.ID) + correctiveBody := assessmentAttemptCorrectiveBody(t, acceptedAttempt.Specialization, "intern", acceptedAttempt.ID) + corrective := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction", "198.51.100.8:1234") + if corrective.Code != http.StatusCreated { + t.Fatalf("create lower-grade correction = %d %s", corrective.Code, corrective.Body.String()) + } + var correctiveSnapshot struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + RootAttemptID uuid.UUID `json:"root_attempt_id"` + } + if err := json.Unmarshal(corrective.Body.Bytes(), &correctiveSnapshot); err != nil || correctiveSnapshot.ID == uuid.Nil || + correctiveSnapshot.Kind != "corrective" || correctiveSnapshot.RootAttemptID != acceptedAttempt.ID { + t.Fatalf("corrective snapshot = %+v, decode error %v; want root linkage", correctiveSnapshot, err) + } + if _, correctiveDeadline := readAttemptChainTiming(t, ctx, harness.pool, correctiveSnapshot.ID); !correctiveDeadline.Equal(rootDeadline) { + t.Fatalf("corrective database chain deadline = %s, want exact root deadline %s", correctiveDeadline, rootDeadline) + } + var rootCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'`, candidate.ID).Scan(&rootCount); err != nil || rootCount != 1 { + t.Fatalf("candidate root attempt count = %d, error %v; corrective must not consume root quota", rootCount, err) + } + terminalizeAttempt(t, ctx, harness.pool, correctiveSnapshot.ID) + repeatedGrade := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction-repeat", "198.51.100.9:1234") + if repeatedGrade.Code != http.StatusBadRequest || !strings.Contains(repeatedGrade.Body.String(), "/target_grade") { + t.Fatalf("repeat corrective grade = %d %s, want field error at target_grade", repeatedGrade.Code, repeatedGrade.Body.String()) + } + var correctionCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='corrective'`, candidate.ID).Scan(&correctionCount); err != nil || correctionCount != 1 { + t.Fatalf("candidate correction count = %d, error %v; repeated grade must not add a row", correctionCount, err) + } + + // The typed 201 training outcome is replaced only after its generic + // idempotency window expires; the active training attempt yields a new 409. + trainingScope := harness.keyring.IdempotencyScope("assessment_attempt.create", "attempt-training", candidate.ID.String()) + if _, err := harness.pool.Exec(ctx, ` + WITH stamp AS (SELECT clock_timestamp() AS at) + UPDATE idempotency_records + SET created_at=stamp.at-interval '2 minutes', expires_at=stamp.at-interval '1 second' + FROM stamp WHERE scope_hash=$1`, trainingScope[:]); err != nil { + t.Fatalf("expire training idempotency fixture: %v", err) + } + expiredTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234") + requireSessionProblem(t, expiredTrainingKey, http.StatusConflict, "state_conflict") + reusedTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234") + assertAssessmentAttemptReplay(t, "attempt-training after expiry", expiredTrainingKey, reusedTrainingKey) + + // Fail the item insert after the attempt header and idempotency reservation + // have been written. A same-key retry after removing the trigger must work, + // proving that the entire PostgreSQL transaction rolled back. + if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "198.51.100.11:1234"); response.Code != http.StatusOK { + t.Fatalf("save rollback candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "198.51.100.12:1234") + if _, err := harness.pool.Exec(ctx, `CREATE FUNCTION reject_attempt_item_for_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION USING ERRCODE='23514', CONSTRAINT='test_attempt_item_rejected', MESSAGE='test failure'; END; $$`); err != nil { + t.Fatalf("create attempt-item rollback trigger function: %v", err) + } + if _, err := harness.pool.Exec(ctx, `CREATE TRIGGER reject_attempt_item_for_test BEFORE INSERT ON assessment_attempt_items FOR EACH ROW EXECUTE FUNCTION reject_attempt_item_for_test()`); err != nil { + t.Fatalf("create attempt-item rollback trigger: %v", err) + } + rollbackBody := assessmentAttemptCreateBody(t, "backend") + rollbackKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody, + sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234") + if rollbackKey.Code != http.StatusInternalServerError { + t.Fatalf("forced item insert failure = %d %s, want internal error", rollbackKey.Code, rollbackKey.Body.String()) + } + if _, err := harness.pool.Exec(ctx, `DROP TRIGGER reject_attempt_item_for_test ON assessment_attempt_items`); err != nil { + t.Fatalf("drop attempt-item rollback trigger: %v", err) + } + if _, err := harness.pool.Exec(ctx, `DROP FUNCTION reject_attempt_item_for_test()`); err != nil { + t.Fatalf("drop attempt-item rollback trigger function: %v", err) + } + assertAttemptCount(t, ctx, harness.pool, 3) + retryAfterRollback := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody, + sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234") + if retryAfterRollback.Code != http.StatusCreated { + t.Fatalf("same-key create after rollback = %d %s, want 201", retryAfterRollback.Code, retryAfterRollback.Body.String()) + } + assertAttemptCount(t, ctx, harness.pool, 4) + assertAttemptPinAndItemRowsAreImmutable(t, ctx, harness.pool, acceptedAttempt.ID) +} + +func TestAssessmentAttemptSessionUsesDatabaseTimeAfterRowLockWait(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-lock-wait@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set lock-wait candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.10:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.11:1234"); response.Code != http.StatusOK { + t.Fatalf("save lock-wait candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.12:1234") + created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", assessmentAttemptCreateBody(t, "backend"), + sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-create", "203.0.113.13:1234") + if created.Code != http.StatusCreated { + t.Fatalf("create lock-wait attempt = %d %s", created.Code, created.Body.String()) + } + var attempt struct { + ID uuid.UUID `json:"id"` + } + if err := json.Unmarshal(created.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil { + t.Fatalf("decode lock-wait attempt ID = %s, error %v", attempt.ID, err) + } + + lockConnection, err := harness.pool.Acquire(ctx) + if err != nil { + t.Fatalf("acquire row-lock connection: %v", err) + } + defer lockConnection.Release() + lockTx, err := lockConnection.Begin(ctx) + if err != nil { + t.Fatalf("begin row-lock transaction: %v", err) + } + defer func() { + if err := lockTx.Rollback(context.Background()); err != nil && !errors.Is(err, pgx.ErrTxClosed) { + t.Errorf("rollback row-lock transaction: %v", err) + } + }() + var lockPID int32 + if err := lockConnection.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&lockPID); err != nil { + t.Fatalf("read row-lock backend PID: %v", err) + } + var lockedID uuid.UUID + if err := lockTx.QueryRow(ctx, `SELECT id FROM assessment_attempts WHERE id=$1 FOR UPDATE`, attempt.ID).Scan(&lockedID); err != nil || lockedID != attempt.ID { + t.Fatalf("lock attempt row %s: got %s, error %v", attempt.ID, lockedID, err) + } + + type requestResult struct { + response *httptest.ResponseRecorder + } + result := make(chan requestResult, 1) + go func() { + response := assessmentAttemptHTTPRequestWithTimeout(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-session", "203.0.113.14:1234", 100*time.Second) + result <- requestResult{response: response} + }() + waitForAssessmentAttemptRowLock(t, ctx, harness.pool, lockPID) + waitForAttemptIdleDeadline(t, ctx, harness.pool, attempt.ID) + if err := lockTx.Commit(ctx); err != nil { + t.Fatalf("release row lock after idle timeout: %v", err) + } + select { + case completed := <-result: + if completed.response.Code != http.StatusOK { + t.Fatalf("session after lock-wait expiry = %d %s; server logs: %s", + completed.response.Code, completed.response.Body.String(), harness.logs.String()) + } + var snapshot struct { + Version int64 `json:"version"` + State string `json:"state"` + Sessions struct { + Used int32 `json:"used"` + } `json:"sessions"` + } + if err := json.Unmarshal(completed.response.Body.Bytes(), &snapshot); err != nil || snapshot.Version != 2 || + snapshot.State != "expired" || snapshot.Sessions.Used != 1 { + t.Fatalf("session response after deadline = %+v, error %v; want expired version 2 and one session", snapshot, err) + } + case <-time.After(30 * time.Second): + t.Fatal("session request did not finish after releasing attempt row lock") + } +} + +type assessmentAttemptHTTPHarness struct { + *sessionHTTPHarness + keyring *identity.Keyring +} + +func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *assessmentAttemptHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentHandler := v1.NewConsentHandler( + consent.NewQueryService(consentStore, time.Now), consent.NewService(transactor, time.Now), + ) + questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now)) + catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor)) + attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, clock.Now) + if err != nil { + t.Fatalf("NewAttemptService() error = %v", err) + } + attemptHandler := v1.NewAssessmentHandler(attemptService) + signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now) + if err != nil { + t.Fatalf("NewSignalService() error = %v", err) + } + signalHandler := v1.NewAssessmentSignalHandler(signalService) + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), + v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler), + v1.WithAssessment(attemptHandler), v1.WithAssessmentSignals(signalHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + base := &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} + return &assessmentAttemptHTTPHarness{sessionHTTPHarness: base, keyring: keyring} +} + +func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + transactor := postgresadapter.NewTransactor(pool) + bank := assessment.NewBank(transactor) + store := postgresadapter.NewAssessmentBankStore(pool) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now) + fixture := assessmentFixture{ + ctx: ctx, pool: pool, store: store, transactor: transactor, + bank: bank, publisher: publisher, demoBundle: loadDemoBundleFile(t), + } + productPolicy := integrationPolicy(11) + productPolicy.Assessment.MaxAttemptsPerWindow = 1 + demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment + productPolicy.Assessment.Attempt = demoAttemptPolicy.Attempt + productPolicy.Assessment.Training = demoAttemptPolicy.Training + productPolicy.Assessment.Attempt.MaxSessions = 1 + productPolicy.Assessment.Attempt.IdleTimeoutSeconds = 60 + policyVersion, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, Policy: productPolicy, + }) + if err != nil { + t.Fatalf("Publish(attempt fixture policy) error = %v", err) + } + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + bundle := fixture.reviewedBundle(int(required)) + bundle.Name = "assessment-attempt-backend-fixture" + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(backend attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, bundle) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior) + + frontend := bundle + frontend.Name = "assessment-attempt-frontend-fixture" + frontend.Category = "frontend" + frontend.Families = append([]assessment.BundleFamily(nil), bundle.Families...) + for index := range frontend.Families { + frontend.Families[index].Key = fmt.Sprintf("attempt-frontend-%02d", index+1) + frontend.Families[index].Specialization = "frontend" + } + if _, err := bank.ImportBundle(ctx, frontend); err != nil { + t.Fatalf("ImportBundle(frontend attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontend) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend"), domain.SpecializationFrontend, domain.GradeJunior) + + backendIntern := fixture.reviewedBundle(int(required)) + backendIntern.Name = "assessment-attempt-backend-intern-fixture" + backendIntern.Category = "backend-intern" + for index := range backendIntern.Families { + backendIntern.Families[index].Key = fmt.Sprintf("attempt-backend-intern-%02d", index+1) + } + if _, err := bank.ImportBundle(ctx, backendIntern); err != nil { + t.Fatalf("ImportBundle(backend intern attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, backendIntern) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend-intern"), domain.SpecializationBackend, domain.GradeIntern) + + frontendIntern := fixture.reviewedBundle(int(required)) + frontendIntern.Name = "assessment-attempt-frontend-intern-fixture" + frontendIntern.Category = "frontend-intern" + for index := range frontendIntern.Families { + frontendIntern.Families[index].Key = fmt.Sprintf("attempt-frontend-intern-%02d", index+1) + frontendIntern.Families[index].Specialization = "frontend" + } + if _, err := bank.ImportBundle(ctx, frontendIntern); err != nil { + t.Fatalf("ImportBundle(frontend intern attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontendIntern) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend-intern"), domain.SpecializationFrontend, domain.GradeIntern) + + training := fixture.reviewedBundle(int(policyVersion.Policy().Assessment.Training.DemoExpressItemCount)) + training.Name = "assessment-attempt-training-fixture" + training.Category = "training-attempts" + for index := range training.Families { + training.Families[index].Key = fmt.Sprintf("attempt-training-%02d", index+1) + } + if _, err := bank.ImportBundle(ctx, training); err != nil { + t.Fatalf("ImportBundle(training attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, training) + seedAssessmentAttemptTrainingBinding(ctx, t, pool, policyVersion.ID().UUID(), training.Category, len(training.Families)) +} + +func publishAssessmentAttemptFixtureFamilies(ctx context.Context, t *testing.T, bank *assessment.Bank, bundle assessment.Bundle) { + t.Helper() + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } +} + +func openAssessmentAttemptFixtureCategory( + ctx context.Context, + t *testing.T, + bank *assessment.Bank, + policyID domain.PolicyVersionID, + category domain.AssessmentCategory, + specialization domain.SpecializationCode, + grade domain.GradeCode, +) { + t.Helper() + metadata, err := domain.NewAssessmentCategoryCatalogMetadata(specialization, grade, []domain.TaskLanguageCode{domain.TaskLanguageGo}) + if err != nil { + t.Fatalf("NewAssessmentCategoryCatalogMetadata(%s) error = %v", specialization, err) + } + if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: category, GradingPolicyID: policyID, OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }); err != nil { + t.Fatalf("OpenCategory(%s) error = %v", category, err) + } +} + +func seedAssessmentAttemptTrainingBinding( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + policyID uuid.UUID, + category string, + itemCount int, +) { + t.Helper() + type manifestEntry struct { + FamilyKey string `json:"family_key"` + Version int32 `json:"version"` + ContentSHA256 string `json:"content_sha256"` + } + type familyRecord struct { + ID uuid.UUID + Entry manifestEntry + Hash []byte + } + rows, err := pool.Query(ctx, ` + SELECT id, family_key, version, content_sha256 + FROM assessment_families + WHERE category=$1 AND lifecycle='published' + ORDER BY family_key, version`, category) + if err != nil { + t.Fatalf("read published training family fixture: %v", err) + } + var families []familyRecord + for rows.Next() { + var family familyRecord + if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil { + rows.Close() + t.Fatalf("scan training family fixture: %v", err) + } + family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash) + families = append(families, family) + } + if err := rows.Err(); err != nil { + rows.Close() + t.Fatalf("iterate training family fixture: %v", err) + } + rows.Close() + if len(families) != itemCount { + t.Fatalf("published training family count = %d, want %d", len(families), itemCount) + } + manifest, err := json.Marshal(func() []manifestEntry { + entries := make([]manifestEntry, len(families)) + for index := range families { + entries[index] = families[index].Entry + } + return entries + }()) + if err != nil { + t.Fatalf("marshal training family manifest: %v", err) + } + canonical := []byte("lincodex.assessment.category-manifest.v1\x00") + for _, family := range families { + key := []byte(family.Entry.FamilyKey) + if len(key) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size { + t.Fatalf("training family manifest entry is out of range") + } + canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key))) + canonical = append(canonical, key...) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version)) + canonical = append(canonical, family.Hash...) + } + manifestHash := sha256.Sum256(canonical) + bindingID := uuid.New() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin reviewed training binding fixture: %v", err) + } + defer tx.Rollback(ctx) + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_bindings ( + id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`, + bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil { + t.Fatalf("insert reviewed training binding fixture: %v", err) + } + for index, family := range families { + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_binding_families ( + binding_id, ordinal, family_id, family_key, family_version, content_sha256 + ) VALUES ($1,$2,$3,$4,$5,$6)`, bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil { + t.Fatalf("insert reviewed training family member %s: %v", family.Entry.FamilyKey, err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit reviewed training binding fixture: %v", err) + } + _, err = pool.Exec(ctx, ` + INSERT INTO assessment_category_openings ( + id, category, policy_version_id, opened_by, required_families, published_families, opened_at + ) VALUES (gen_random_uuid(), $1, $2, 'operator:fixture-opener', 1, $3, clock_timestamp())`, category, policyID, itemCount) + assertPgError(t, "open a training-only category for real assessments", err, "23514", "assessment_training_category_is_disjoint") +} + +func assessmentAttemptCreateBody(t *testing.T, specialization string) string { + t.Helper() + return assessmentAttemptCreateBodyWithGrade(t, specialization, "junior") +} + +func assessmentAttemptCreateBodyWithGrade(t *testing.T, specialization, grade string) string { + t.Helper() + body, err := json.Marshal(map[string]string{ + "kind": "root", "specialization": specialization, "target_grade": grade, "task_language": "go", + }) + if err != nil { + t.Fatalf("marshal assessment create body: %v", err) + } + return string(body) +} + +func assessmentAttemptCorrectiveBody(t *testing.T, specialization, grade string, rootID uuid.UUID) string { + t.Helper() + body, err := json.Marshal(map[string]string{ + "kind": "corrective", "specialization": specialization, "target_grade": grade, + "task_language": "go", "root_attempt_id": rootID.String(), + }) + if err != nil { + t.Fatalf("marshal corrective attempt body: %v", err) + } + return string(body) +} + +func assessmentAttemptQuestionnaireRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "specializations": []any{ + map[string]any{"specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil}, + map[string]any{"specialization": "frontend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil}, + }, + "work_context": map[string]any{"work_formats": []string{"remote"}}, + }) + if err != nil { + t.Fatalf("marshal attempt questionnaire: %v", err) + } + return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body), + sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr) +} + +func grantCurrentAttemptConsent( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie *http.Cookie, + csrf, remoteAddr string, +) { + t.Helper() + textResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/consent-texts/c3", "", + "", cookie.Value, "", "", remoteAddr) + var current struct { + TextVersion string `json:"text_version"` + } + if textResponse.Code != http.StatusOK || json.Unmarshal(textResponse.Body.Bytes(), ¤t) != nil || current.TextVersion == "" { + t.Fatalf("read current C3 text = %d %s", textResponse.Code, textResponse.Body.String()) + } + grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin) + if grant.Code != http.StatusOK { + t.Fatalf("grant current C3 = %d %s", grant.Code, grant.Body.String()) + } +} + +func assessmentAttemptHTTPRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string, +) *httptest.ResponseRecorder { + return assessmentAttemptHTTPRequestWithTimeout(t, harness, method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr, 20*time.Second) +} + +func assessmentAttemptHTTPRequestWithTimeout( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string, + timeout time.Duration, +) *httptest.ResponseRecorder { + t.Helper() + requestContext, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + request := httptest.NewRequest(method, path, strings.NewReader(body)).WithContext(requestContext) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + if idempotencyKey != "" { + request.Header.Set("Idempotency-Key", idempotencyKey) + } + request.RemoteAddr = remoteAddr + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +func assertAttemptCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int64) { + t.Helper() + var got int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts").Scan(&got); err != nil { + t.Fatalf("count assessment attempts: %v", err) + } + if got != want { + t.Fatalf("assessment attempt rows = %d, want %d", got, want) + } +} + +func readAttemptChainTiming(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) (time.Time, time.Time) { + t.Helper() + var createdAt, deadline time.Time + if err := pool.QueryRow(ctx, `SELECT created_at, chain_deadline FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&createdAt, &deadline); err != nil { + t.Fatalf("read assessment root chain deadline: %v", err) + } + return createdAt.UTC(), deadline.UTC() +} + +func terminalizeAttempt(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + command, err := pool.Exec(ctx, ` + WITH stamp AS ( + SELECT GREATEST(clock_timestamp(), last_activity_at) AS at + FROM assessment_attempts WHERE id=$1 + ) + UPDATE assessment_attempts AS attempt + SET state='completed', outcome='not_confirmed', ended_at=stamp.at, + updated_at=stamp.at, version=attempt.version+1 + FROM stamp + WHERE attempt.id=$1 AND attempt.state='in_progress'`, attemptID) + if err != nil || command.RowsAffected() != 1 { + t.Fatalf("terminalize assessment attempt = %d rows, error %v", command.RowsAffected(), err) + } +} + +func assertAttemptPinAndItemRowsAreImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + _, err := pool.Exec(ctx, ` + UPDATE assessment_attempts + SET product_policy_version=product_policy_version+1, version=version+1, updated_at=clock_timestamp() + WHERE id=$1`, attemptID) + assertPgError(t, "change immutable attempt policy pin", err, "23000", "assessment_attempt_pins_immutable") + _, err = pool.Exec(ctx, ` + UPDATE assessment_attempt_items + SET variant=variant || '{"changed":true}'::jsonb + WHERE attempt_id=$1 AND ordinal=1`, attemptID) + assertPgError(t, "change immutable attempt item variant", err, "23000", "assessment_attempt_item_immutable") + _, err = pool.Exec(ctx, `DELETE FROM assessment_attempt_items WHERE attempt_id=$1 AND ordinal=1`, attemptID) + assertPgError(t, "delete immutable attempt item", err, "23000", "assessment_attempt_item_delete_forbidden") +} + +func assertAssessmentAttemptReplay(t *testing.T, key string, original, replay *httptest.ResponseRecorder) { + t.Helper() + if original.Code != replay.Code { + t.Fatalf("create replay %s status = %d, want stored status %d", key, replay.Code, original.Code) + } + if original.Code == http.StatusCreated { + if replay.Body.String() != original.Body.String() { + t.Fatalf("created attempt replay %s body differs from its immutable response", key) + } + return + } + type stableProblem struct { + Type string `json:"type"` + Title string `json:"title"` + Status int `json:"status"` + Code string `json:"code"` + Detail string `json:"detail"` + } + var originalProblem, replayProblem stableProblem + if err := json.Unmarshal(original.Body.Bytes(), &originalProblem); err != nil { + t.Fatalf("decode original conflict response: %v", err) + } + if err := json.Unmarshal(replay.Body.Bytes(), &replayProblem); err != nil { + t.Fatalf("decode replay conflict response: %v", err) + } + if originalProblem != replayProblem || replayProblem.Code != "state_conflict" { + t.Fatalf("create replay %s stable problem = %+v, want %+v", key, replayProblem, originalProblem) + } +} + +type assessmentAttemptStoredState struct { + Version int64 + Sessions int32 + State string +} + +func readAttemptStoredState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) assessmentAttemptStoredState { + t.Helper() + var state assessmentAttemptStoredState + err := pool.QueryRow(ctx, ` + SELECT version, sessions_used, state + FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&state.Version, &state.Sessions, &state.State) + if err != nil { + t.Fatalf("read stored assessment attempt state: %v", err) + } + return state +} + +func waitForAssessmentAttemptRowLock(t *testing.T, ctx context.Context, pool *pgxpool.Pool, blockingPID int32) { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + var waiting int64 + err := pool.QueryRow(ctx, ` + SELECT count(*) + FROM pg_stat_activity + WHERE wait_event_type='Lock' + AND $1 = ANY(pg_blocking_pids(pid)) + AND query ILIKE '%assessment_attempts%'`, blockingPID).Scan(&waiting) + if err != nil { + t.Fatalf("inspect blocked attempt session request: %v", err) + } + if waiting > 0 { + return + } + select { + case <-ctx.Done(): + t.Fatalf("wait for attempt row lock: %v", ctx.Err()) + case <-time.After(50 * time.Millisecond): + } + } + t.Fatal("session command never waited on the locked assessment_attempts row") +} + +func waitForAttemptIdleDeadline(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + deadline := time.Now().Add(90 * time.Second) + for time.Now().Before(deadline) { + var expired bool + err := pool.QueryRow(ctx, ` + SELECT last_activity_at + idle_timeout_seconds * interval '1 second' <= clock_timestamp() + FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&expired) + if err != nil { + t.Fatalf("read attempt idle deadline: %v", err) + } + if expired { + return + } + select { + case <-ctx.Done(): + t.Fatalf("wait for attempt idle deadline: %v", ctx.Err()) + case <-time.After(100 * time.Millisecond): + } + } + t.Fatal("assessment attempt idle deadline did not pass during the row lock") +} diff --git a/backend/integration_test/assessment_availability_http_test.go b/backend/integration_test/assessment_availability_http_test.go new file mode 100644 index 0000000..80e198b --- /dev/null +++ b/backend/integration_test/assessment_availability_http_test.go @@ -0,0 +1,509 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + assessmentpolicy "lincodex/backend/internal/usecase/policy" +) + +type assessmentAvailabilityHTTPGrade struct { + Grade string `json:"grade"` + Status string `json:"status"` + Mode *string `json:"mode"` + TimeLimitSeconds *int32 `json:"time_limit_seconds"` + MaxSessions *int32 `json:"max_sessions"` + MaxItems *int32 `json:"max_items"` + PracticeRequired *bool `json:"practice_required"` +} + +type assessmentAvailabilityHTTPSpecialization struct { + Specialization string `json:"specialization"` + ActiveAttempt *uuid.UUID `json:"active_attempt_id"` + Grades []assessmentAvailabilityHTTPGrade `json:"grades"` +} + +type assessmentAvailabilityHTTPProjection struct { + Specializations []assessmentAvailabilityHTTPSpecialization `json:"specializations"` +} + +func TestAssessmentAvailabilityHTTPIsCandidateScopedAndReadOnly(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-http-candidate@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.50:1234") + + unauthenticated := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", "", "", "", "203.0.113.51:1234") + requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated") + employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "availability-http-employer@example.test", passwordHash) + employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "203.0.113.52:1234") + employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", employerCookie.Value, "", "", "203.0.113.53:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + + path := "/api/v1/me/assessment-availability" + emptyRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.54:1234") + var emptyProjection struct { + Specializations []json.RawMessage `json:"specializations"` + } + if emptyRead.Code != http.StatusOK || emptyRead.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(emptyRead.Body.Bytes(), &emptyProjection) != nil || emptyProjection.Specializations == nil || len(emptyProjection.Specializations) != 0 { + t.Fatalf("availability before questionnaire = %d %s, Cache-Control=%q, want empty candidate projection", + emptyRead.Code, emptyRead.Body.String(), emptyRead.Header().Get("Cache-Control")) + } + if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "203.0.113.55:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "203.0.113.56:1234") + + available := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.57:1234") + var initial assessmentAvailabilityHTTPProjection + if available.Code != http.StatusOK || available.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(available.Body.Bytes(), &initial) != nil || len(initial.Specializations) != 2 { + t.Fatalf("availability after questionnaire = %d %s, Cache-Control=%q, want both saved specializations", + available.Code, available.Body.String(), available.Header().Get("Cache-Control")) + } + backend := findAssessmentAvailabilitySpecialization(t, initial, "backend") + for _, target := range []string{"intern", "junior"} { + grade := findAssessmentAvailabilityGrade(t, backend, target) + if grade.Status != "available" || grade.Mode == nil || *grade.Mode != "demo_basic" || + grade.TimeLimitSeconds == nil || *grade.TimeLimitSeconds != 72*60*60 || + grade.MaxSessions == nil || *grade.MaxSessions != 1 || grade.MaxItems == nil || *grade.MaxItems != 13 || + grade.PracticeRequired == nil || *grade.PracticeRequired { + t.Fatalf("backend %s availability = %+v, response=%s, want the published demo_basic start limits", + target, grade, available.Body.String()) + } + } + + // The questionnaire self-assesses junior, while this request selects the + // offered intern bank. The stored questionnaire grade is not a target gate. + created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "intern"), sessionHTTPTestOrigin, + candidateCookie.Value, candidateCSRF, "availability-create-different-grade", "203.0.113.58:1234") + var activeAttempt assessmentAnswerHTTPAttempt + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &activeAttempt) != nil || activeAttempt.ID == uuid.Nil { + t.Fatalf("create attempt at offered grade different from self-assessment = %d %s", created.Code, created.Body.String()) + } + + // Re-login immediately before the read-only measurement so the session + // activity coalescing window cannot obscure a write caused by the GET. + candidateCookie, candidateCSRF = loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.59:1234") + token, err := domain.ParseSecretToken(candidateCookie.Value) + if err != nil { + t.Fatalf("parse synthetic session token for state comparison: %v", err) + } + tokenHash := token.Hash() + type availabilityReadState struct { + attemptVersion int64 + sessionsUsed int32 + updatedAt time.Time + sessionSeenAt time.Time + attemptRows int64 + itemRows int64 + answeredItems int64 + idempotency int64 + } + readAvailabilityState := func() availabilityReadState { + t.Helper() + var state availabilityReadState + if err := harness.pool.QueryRow(ctx, "SELECT version, sessions_used, updated_at FROM assessment_attempts WHERE id=$1", activeAttempt.ID). + Scan(&state.attemptVersion, &state.sessionsUsed, &state.updatedAt); err != nil { + t.Fatalf("read attempt state before/after availability: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT last_seen_at FROM sessions WHERE token_hash=$1", tokenHash[:]).Scan(&state.sessionSeenAt); err != nil { + t.Fatalf("read session activity before/after availability: %v", err) + } + if err := harness.pool.QueryRow(ctx, ` + SELECT (SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'), + (SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2), + (SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2 AND answered_at IS NOT NULL), + (SELECT count(*) FROM idempotency_records)`, candidate.ID, activeAttempt.ID). + Scan(&state.attemptRows, &state.itemRows, &state.answeredItems, &state.idempotency); err != nil { + t.Fatalf("read attempt/quota state before/after availability: %v", err) + } + return state + } + before := readAvailabilityState() + for index := 0; index < 2; index++ { + response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.60:1234") + var current assessmentAvailabilityHTTPProjection + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(response.Body.Bytes(), ¤t) != nil { + t.Fatalf("repeated availability GET %d = %d %s, Cache-Control=%q", index+1, response.Code, + response.Body.String(), response.Header().Get("Cache-Control")) + } + backend = findAssessmentAvailabilitySpecialization(t, current, "backend") + if backend.ActiveAttempt == nil || *backend.ActiveAttempt != activeAttempt.ID { + t.Fatalf("repeated availability GET %d active attempt = %v, want %s", index+1, backend.ActiveAttempt, activeAttempt.ID) + } + for _, grade := range backend.Grades { + if grade.Status != "active_attempt" { + t.Fatalf("backend grade %s status = %q while an attempt is active", grade.Grade, grade.Status) + } + } + } + after := readAvailabilityState() + if before.attemptVersion != after.attemptVersion || before.sessionsUsed != after.sessionsUsed || + !before.updatedAt.Equal(after.updatedAt) || !before.sessionSeenAt.Equal(after.sessionSeenAt) || + before.attemptRows != after.attemptRows || before.itemRows != after.itemRows || + before.answeredItems != after.answeredItems || before.idempotency != after.idempotency { + t.Fatalf("availability GET wrote state: before=%+v after=%+v", before, after) + } + + adaptive := domain.DemoProductPolicyV2() + adaptive.Assessment.Calibration = domain.AssessmentCalibrationCalibrated + adaptive.Assessment.Attempt.RealMode = domain.AssessmentRealModeAdaptive + adaptive.Assessment.Attempt.BasicPassMark = 0 + publisher := assessmentpolicy.NewPublisher(postgres.NewPolicyStore(harness.pool).Policies(), time.Now) + adaptiveVersion, err := publisher.Publish(ctx, assessmentpolicy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: adaptive, + }) + if err != nil { + t.Fatalf("publish explicit adaptive policy for unavailable-mode check: %v", err) + } + adaptiveBank := assessment.NewBank(postgres.NewTransactor(harness.pool)) + adaptiveFixture := assessmentFixture{ + ctx: ctx, pool: harness.pool, store: postgres.NewAssessmentBankStore(harness.pool), + transactor: postgres.NewTransactor(harness.pool), bank: adaptiveBank, + demoBundle: loadDemoBundleFile(t), + } + adaptiveRequired, err := domain.RequiredPublishedAssessmentFamilies(adaptiveVersion.Policy()) + if err != nil { + t.Fatalf("read adaptive policy family requirement: %v", err) + } + var publishedBackendFamilies int32 + if err := harness.pool.QueryRow(ctx, ` + SELECT count(DISTINCT family_key)::integer + FROM assessment_families + WHERE category='backend' AND lifecycle='published' AND review_status='approved'`).Scan(&publishedBackendFamilies); err != nil { + t.Fatalf("count current backend families for adaptive opening: %v", err) + } + if publishedBackendFamilies < adaptiveRequired { + adaptiveBundle := adaptiveFixture.reviewedBundle(int(adaptiveRequired - publishedBackendFamilies)) + adaptiveBundle.Name = "availability-adaptive-backend" + adaptiveBundle.Category = "backend" + for index := range adaptiveBundle.Families { + adaptiveBundle.Families[index].Key = fmt.Sprintf("availability-adaptive-backend-%02d", index+1) + adaptiveBundle.Families[index].Specialization = string(domain.SpecializationBackend) + } + if _, err := adaptiveBank.ImportBundle(ctx, adaptiveBundle); err != nil { + t.Fatalf("import additional reviewed backend families for adaptive opening: %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, adaptiveBank, adaptiveBundle) + } + openAssessmentAttemptFixtureCategory( + ctx, t, adaptiveBank, adaptiveVersion.ID(), domain.AssessmentCategory("backend"), + domain.SpecializationBackend, domain.GradeJunior, + ) + adaptiveCandidate := createSessionHTTPUser( + ctx, t, harness.sessionHTTPHarness, "availability-adaptive-candidate@example.test", passwordHash, true, + ) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", adaptiveCandidate.ID); err != nil { + t.Fatalf("set adaptive candidate onboarding step: %v", err) + } + adaptiveCookie, adaptiveCSRF := loginConsentHTTP( + t, harness.sessionHTTPHarness, adaptiveCandidate.Email.Address(), "203.0.113.63:1234", + ) + if response := assessmentAvailabilityBackendQuestionnaireRequest(t, harness, adaptiveCookie.Value, adaptiveCSRF, "203.0.113.64:1234"); response.Code != http.StatusOK { + t.Fatalf("save adaptive candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, adaptiveCookie, adaptiveCSRF, "203.0.113.65:1234") + unsupported := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", adaptiveCookie.Value, "", "", "203.0.113.66:1234") + requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented") + var rootCountBefore, idempotencyBefore int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID). + Scan(&rootCountBefore); err != nil { + t.Fatalf("read adaptive candidate root attempt count before denied POST: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyBefore); err != nil { + t.Fatalf("read idempotency count before denied adaptive POST: %v", err) + } + adaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin, + adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.67:1234") + requireSessionProblem(t, adaptiveCreate, http.StatusConflict, "state_conflict") + var rootCountAfter int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID). + Scan(&rootCountAfter); err != nil { + t.Fatalf("read root attempts after unsupported adaptive create: %v", err) + } + var idempotencyAfter int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfter); err != nil { + t.Fatalf("read idempotency count after denied adaptive POST: %v", err) + } + if rootCountAfter != rootCountBefore { + t.Fatalf("unsupported adaptive create changed root attempt count from %d to %d", rootCountBefore, rootCountAfter) + } + if idempotencyAfter != idempotencyBefore+1 { + t.Fatalf("unsupported adaptive create idempotency row count = %d, want one immutable 409 outcome after %d", idempotencyAfter, idempotencyBefore) + } + replayedAdaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin, + adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.68:1234") + requireSessionProblem(t, replayedAdaptiveCreate, http.StatusConflict, "state_conflict") + var idempotencyAfterReplay int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfterReplay); err != nil { + t.Fatalf("read idempotency count after adaptive 409 replay: %v", err) + } + if idempotencyAfterReplay != idempotencyAfter { + t.Fatalf("adaptive 409 replay added idempotency rows: before replay=%d after=%d", idempotencyAfter, idempotencyAfterReplay) + } +} + +func assessmentAvailabilityBackendQuestionnaireRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "specializations": []any{ + map[string]any{ + "specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, + "stack": []string{}, "experience": nil, + }, + }, + "work_context": map[string]any{"work_formats": []string{"remote"}}, + }) + if err != nil { + t.Fatalf("marshal backend-only adaptive questionnaire: %v", err) + } + return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body), + sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr) +} + +func createAssessmentAvailabilityEmployer( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, + RegisteredAt: harness.clock.Now().Truncate(time.Microsecond), + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create synthetic employer: %v", err) + } + verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, + harness.clock.Now().Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + return verified +} + +func findAssessmentAvailabilitySpecialization( + t *testing.T, + availability assessmentAvailabilityHTTPProjection, + want string, +) assessmentAvailabilityHTTPSpecialization { + t.Helper() + for _, specialization := range availability.Specializations { + if specialization.Specialization == want { + return specialization + } + } + t.Fatalf("availability does not contain specialization %q", want) + return assessmentAvailabilityHTTPSpecialization{} +} + +func findAssessmentAvailabilityGrade( + t *testing.T, + specialization assessmentAvailabilityHTTPSpecialization, + want string, +) assessmentAvailabilityHTTPGrade { + t.Helper() + for _, grade := range specialization.Grades { + if grade.Grade == want { + return grade + } + } + t.Fatalf("availability for %q does not contain grade %q", specialization.Specialization, want) + return assessmentAvailabilityHTTPGrade{} +} + +func TestAssessmentDisclosedFamilyCutoffUsesItemDisclosureTime(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234") + + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, + "availability-disclosure-create", "203.0.113.43:1234") + var attempt assessmentAnswerHTTPAttempt + if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String()) + } + items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) + if len(items) < 3 { + t.Fatalf("frozen item count = %d, want at least three items", len(items)) + } + var createdAt time.Time + if err := harness.pool.QueryRow(ctx, "SELECT created_at FROM assessment_attempts WHERE id=$1", attempt.ID).Scan(&createdAt); err != nil { + t.Fatalf("read attempt creation time: %v", err) + } + since := createdAt.UTC().Add(time.Microsecond) + + firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, attempt.Version, items[0], false) + accepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "availability-disclosure-answer", "203.0.113.44:1234") + if accepted.Code != http.StatusOK { + t.Fatalf("answer first item = %d %s", accepted.Code, accepted.Body.String()) + } + _, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, attempt.ID, items[0].ID) + if !answeredAt.After(since) { + t.Fatalf("first answer timestamp %s must be after cutoff %s to establish distinct disclosure times", answeredAt, since) + } + + familyKey := func(itemID uuid.UUID) domain.AssessmentFamilyKey { + t.Helper() + var stored string + if err := harness.pool.QueryRow(ctx, "SELECT family_key FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2", attempt.ID, itemID).Scan(&stored); err != nil { + t.Fatalf("read frozen item family key: %v", err) + } + key, err := domain.ParseAssessmentFamilyKey(stored) + if err != nil { + t.Fatalf("parse frozen item family key: %v", err) + } + return key + } + firstKey, secondKey, thirdKey := familyKey(items[0].ID), familyKey(items[1].ID), familyKey(items[2].ID) + var disclosed []domain.AssessmentFamilyKey + transactor := postgres.NewTransactor(harness.pool) + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + disclosed, readErr = unit.AssessmentAttempts().ListDisclosedFamilyKeys(txctx, candidate.ID, since) + return readErr + }); err != nil { + t.Fatalf("read disclosed family keys after the rolling cutoff: %v", err) + } + contains := func(want domain.AssessmentFamilyKey) bool { + for _, key := range disclosed { + if key == want { + return true + } + } + return false + } + if contains(firstKey) || !contains(secondKey) || contains(thirdKey) { + t.Fatalf("disclosed families = %v; want first excluded, second included, and future third excluded", disclosed) + } + + var countBefore int32 + var latestBefore bool + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + countBefore, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second)) + if readErr != nil { + return readErr + } + _, latestBefore, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization( + txctx, candidate.ID, domain.SpecializationBackend, nil, + ) + return readErr + }); err != nil { + t.Fatalf("read eligible root quota and retry history: %v", err) + } + if countBefore != 1 || !latestBefore { + t.Fatalf("eligible root before platform failure = count %d/latest %v, want 1/true", countBefore, latestBefore) + } + if _, err := harness.pool.Exec(ctx, ` + WITH failure_time AS (SELECT clock_timestamp() AS at) + UPDATE assessment_attempts + SET state='insufficient_bank', + updated_at=failure_time.at, + ended_at=failure_time.at, + version=version+1 + FROM failure_time + WHERE id=$1`, attempt.ID); err != nil { + t.Fatalf("mark isolated attempt as a system bank failure: %v", err) + } + var countAfter int32 + var latestAfter bool + var quotaAfter outbound.AssessmentRootQuotaSnapshot + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + countAfter, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second)) + if readErr != nil { + return readErr + } + _, latestAfter, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization( + txctx, candidate.ID, domain.SpecializationBackend, nil, + ) + if readErr != nil { + return readErr + } + asOf, timeErr := unit.AssessmentBank().DatabaseTime(txctx) + if timeErr != nil { + return timeErr + } + quotaAfter, readErr = unit.AssessmentAttempts().GetRootQuotaSnapshot( + txctx, candidate.ID, createdAt.Add(-time.Second), asOf, 24*time.Hour, 1, + ) + return readErr + }); err != nil { + t.Fatalf("read quota and retry history after platform failure: %v", err) + } + if countAfter != 0 || latestAfter || quotaAfter.Count != 0 || quotaAfter.AvailableAt != nil { + t.Fatalf("platform failure remains in availability history: count=%d latest=%v quota=%+v, want excluded", countAfter, latestAfter, quotaAfter) + } +} diff --git a/backend/integration_test/assessment_bank_test.go b/backend/integration_test/assessment_bank_test.go index 55a5722..9e414fa 100644 --- a/backend/integration_test/assessment_bank_test.go +++ b/backend/integration_test/assessment_bank_test.go @@ -122,7 +122,7 @@ func TestAssessmentBank(t *testing.T) { "edit the version": `UPDATE assessment_families SET version = version + 10`, "edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`, "delete": `DELETE FROM assessment_families`, - "truncate": `TRUNCATE assessment_families`, + "truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events`, } { _, err := fixture.pool.Exec(ctx, statement) assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable") diff --git a/backend/integration_test/assessment_signal_http_test.go b/backend/integration_test/assessment_signal_http_test.go new file mode 100644 index 0000000..235afd3 --- /dev/null +++ b/backend/integration_test/assessment_signal_http_test.go @@ -0,0 +1,442 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +const assessmentSignalHTTPTimeout = 6 * time.Minute + +func TestAssessmentSignalsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentSignalHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.202:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "signal-training", "192.0.2.203:1234") + if trainingCreate.Code != http.StatusCreated { + t.Fatalf("create demo attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + trainingAttempt, trainingItem := assessmentSignalAttemptItem(t, trainingCreate.Body.Bytes()) + grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.204:1234") + + trainingBody := assessmentSignalBody(t, trainingItem, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil) + trainingSignal := submitAssessmentSignal(t, harness, trainingAttempt, cookie, csrf, "signal-demo", trainingBody, "192.0.2.205:1234") + requireSessionProblem(t, trainingSignal, http.StatusConflict, "state_conflict") + + rootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "signal-root", "192.0.2.206:1234") + if rootCreate.Code != http.StatusCreated { + t.Fatalf("create real assessment attempt = %d %s", rootCreate.Code, rootCreate.Body.String()) + } + attemptID, itemID := assessmentSignalAttemptItem(t, rootCreate.Body.Bytes()) + occurredAt := time.Now().UTC().Truncate(time.Microsecond) + body := assessmentSignalBody(t, itemID, occurredAt, "fullscreen_exit", nil) + + badItemBody := assessmentSignalBody(t, uuid.New(), occurredAt, "fullscreen_exit", nil) + badItem := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-bad-item", badItemBody, "192.0.2.207:1234") + if badItem.Code != http.StatusBadRequest { + t.Fatalf("foreign item signal = %d %s, want 400", badItem.Code, badItem.Body.String()) + } + oldTimestampBody := assessmentSignalBody(t, itemID, occurredAt.Add(-10*time.Minute), "fullscreen_exit", nil) + oldTimestamp := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-old-time", oldTimestampBody, "192.0.2.208:1234") + if oldTimestamp.Code != http.StatusBadRequest { + t.Fatalf("out-of-window client timestamp = %d %s, want 400", oldTimestamp.Code, oldTimestamp.Body.String()) + } + + oversizedBody := `{"events":[]}` + strings.Repeat(" ", 32<<10) + oversized := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-oversized", oversizedBody, "192.0.2.209:1234") + requireSessionProblem(t, oversized, http.StatusRequestEntityTooLarge, "payload_too_large") + + accepted := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.210:1234") + assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 1) + if accepted.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("signal receipt Cache-Control = %q, want no-store", accepted.Header().Get("Cache-Control")) + } + var receipt map[string]any + if err := json.Unmarshal(accepted.Body.Bytes(), &receipt); err != nil || len(receipt) != 3 { + t.Fatalf("receipt fields = %+v, decode error %v", receipt, err) + } + for _, privateField := range []string{"events", "item_instance_id", "size_bytes", "answer", "score", "result"} { + if _, exposed := receipt[privateField]; exposed { + t.Fatalf("signal receipt exposed %q", privateField) + } + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1) + assertAssessmentSignalImmutability(t, ctx, harness.pool, attemptID) + + replay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.211:1234") + if replay.Code != accepted.Code || replay.Body.String() != accepted.Body.String() { + t.Fatalf("same-key signal replay = %d %s, want original %d %s", replay.Code, replay.Body.String(), accepted.Code, accepted.Body.String()) + } + changedBody := assessmentSignalBody(t, itemID, occurredAt.Add(time.Second), "fullscreen_exit", nil) + changedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.212:1234") + requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused") + assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1) + expiredScope := harness.keyring.IdempotencyScope("assessment_attempt.signals", "signal-first", candidate.ID.String()) + applicationNow := harness.clock.Now() + if _, err := harness.pool.Exec(ctx, `UPDATE idempotency_records + SET created_at = $2::timestamptz - INTERVAL '25 hours', expires_at = $2::timestamptz - INTERVAL '1 second' + WHERE scope_hash = $1`, expiredScope[:], applicationNow); err != nil { + t.Fatalf("expire signal idempotency scope fixture: %v", err) + } + expiredReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.224:1234") + assertSignalReceipt(t, expiredReplay, http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, attemptID, 2, 2, 1) + + assertAssessmentSignalMeasurementChecks(t, ctx, harness.pool, attemptID, itemID) + + concurrentBodies := []string{ + assessmentSignalBody(t, itemID, occurredAt.Add(2*time.Second), "copy", int32Pointer(12)), + assessmentSignalBody(t, itemID, occurredAt.Add(3*time.Second), "copy", int32Pointer(13)), + } + concurrentResponses := make([]*httptest.ResponseRecorder, len(concurrentBodies)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index := range concurrentBodies { + wait.Add(1) + go func(index int) { + defer wait.Done() + <-start + concurrentResponses[index] = submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-concurrent", concurrentBodies[index], fmt.Sprintf("198.51.100.%d:1234", index+10)) + }(index) + } + close(start) + wait.Wait() + acceptedIndex := -1 + conflictIndex := -1 + for index, response := range concurrentResponses { + switch response.Code { + case http.StatusOK: + acceptedIndex = index + case http.StatusUnprocessableEntity: + requireSessionProblem(t, response, http.StatusUnprocessableEntity, "idempotency_key_reused") + conflictIndex = index + default: + t.Fatalf("concurrent signal %d = %d %s", index, response.Code, response.Body.String()) + } + } + if acceptedIndex < 0 || conflictIndex < 0 || acceptedIndex == conflictIndex { + t.Fatalf("concurrent same-key outcomes accepted=%d conflict=%d", acceptedIndex, conflictIndex) + } + assertSignalReceipt(t, concurrentResponses[acceptedIndex], http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2) + + otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-other@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", otherCandidate.ID); err != nil { + t.Fatalf("set cascade candidate onboarding step: %v", err) + } + otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.213:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "192.0.2.220:1234"); response.Code != http.StatusOK { + t.Fatalf("save cascade candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "192.0.2.221:1234") + foreignAttempt := submitAssessmentSignal(t, harness, attemptID, otherCookie, otherCSRF, "signal-foreign", body, "192.0.2.214:1234") + requireSessionProblem(t, foreignAttempt, http.StatusNotFound, "not_found") + assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2) + otherRootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "signal-cascade", "192.0.2.222:1234") + if otherRootCreate.Code != http.StatusCreated { + t.Fatalf("create cascade candidate attempt = %d %s", otherRootCreate.Code, otherRootCreate.Body.String()) + } + otherAttemptID, otherItemID := assessmentSignalAttemptItem(t, otherRootCreate.Body.Bytes()) + otherSignalBody := assessmentSignalBody(t, otherItemID, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil) + otherAccepted := submitAssessmentSignal(t, harness, otherAttemptID, otherCookie, otherCSRF, "signal-cascade", otherSignalBody, "192.0.2.223:1234") + assertSignalReceipt(t, otherAccepted, http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1) + + revokeC3 := assessmentAttemptHTTPRequest(t, harness, http.MethodDelete, "/api/v1/me/consents/c3", "", + sessionHTTPTestOrigin, cookie.Value, csrf, "", "192.0.2.215:1234") + if revokeC3.Code != http.StatusNoContent { + t.Fatalf("revoke C3 = %d %s", revokeC3.Code, revokeC3.Body.String()) + } + withoutC3 := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-no-c3", body, "192.0.2.216:1234") + requireSessionProblem(t, withoutC3, http.StatusForbidden, "forbidden") + grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.217:1234") + + seedAssessmentSignalCapacity(ctx, t, harness.pool, attemptID, itemID, 10000) + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 2) + saturatedBody := assessmentSignalBody(t, itemID, occurredAt.Add(4*time.Second), "fullscreen_exit", nil) + saturated := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.218:1234") + assertSignalReceipt(t, saturated, http.StatusOK, "saturated", 0) + saturatedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.219:1234") + if saturatedReplay.Body.String() != saturated.Body.String() { + t.Fatalf("saturated replay = %s, want %s", saturatedReplay.Body.String(), saturated.Body.String()) + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 3) + + for next := signalOutcomeCount(t, ctx, harness.pool, attemptID); next < 30; next++ { + key := fmt.Sprintf("signal-rate-%02d", next) + response := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, key, saturatedBody, fmt.Sprintf("203.0.113.%d:1234", next+1)) + assertSignalReceipt(t, response, http.StatusOK, "saturated", 0) + } + limitedKey := "signal-rate-retry" + limited := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, limitedKey, saturatedBody, "203.0.113.80:1234") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("rate-limited signal response omitted Retry-After") + } + scope := harness.keyring.IdempotencyScope("assessment_attempt.signals", limitedKey, candidate.ID.String()) + var consumed int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash = $1", scope[:]).Scan(&consumed); err != nil { + t.Fatalf("check rejected idempotency scope: %v", err) + } + if consumed != 0 { + t.Fatalf("rate-limited idempotency scopes = %d, want 0", consumed) + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 30) + + terminalizeAttempt(t, ctx, harness.pool, attemptID) + terminal := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-terminal", saturatedBody, "203.0.113.81:1234") + requireSessionProblem(t, terminal, http.StatusConflict, "state_conflict") + + if _, err := harness.pool.Exec(ctx, "DELETE FROM assessment_attempts WHERE id = $1", attemptID); err != nil { + t.Fatalf("delete attempt for signal cascade test: %v", err) + } + deletedAttemptReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "203.0.113.82:1234") + requireSessionProblem(t, deletedAttemptReplay, http.StatusNotFound, "not_found") + assertSignalStoredCounts(t, ctx, harness, attemptID, 0, 0, 0) + + _, accountDeleteErr := harness.pool.Exec(ctx, "DELETE FROM users WHERE id = $1", otherCandidate.ID) + assertSQLError(t, "delete account with retained consent history", accountDeleteErr, consentRestrictViolation, "consent_records_subject_id_fkey") + var retainedConsentRecords int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", otherCandidate.ID).Scan(&retainedConsentRecords); err != nil { + t.Fatalf("count retained consent records after rejected account deletion: %v", err) + } + if retainedConsentRecords == 0 { + t.Fatal("account deletion removed the candidate's retained consent records") + } + assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1) +} + +func assessmentSignalAttemptItem(t *testing.T, body []byte) (uuid.UUID, uuid.UUID) { + t.Helper() + var attempt struct { + ID uuid.UUID `json:"id"` + CurrentItem *struct { + ID uuid.UUID `json:"id"` + } `json:"current_item"` + } + if err := json.Unmarshal(body, &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil || attempt.CurrentItem.ID == uuid.Nil { + t.Fatalf("decode signal test attempt and item: %+v, error %v", attempt, err) + } + return attempt.ID, attempt.CurrentItem.ID +} + +func assessmentSignalBody(t *testing.T, itemID uuid.UUID, occurredAt time.Time, kind string, size *int32) string { + t.Helper() + event := map[string]any{ + "kind": kind, "item_instance_id": itemID, "occurred_at": occurredAt.UTC().Format(time.RFC3339Nano), + } + if size != nil { + event["size_bytes"] = *size + } + body, err := json.Marshal(map[string]any{"events": []any{event}}) + if err != nil { + t.Fatalf("marshal signal test body: %v", err) + } + return string(body) +} + +func int32Pointer(value int32) *int32 { return &value } + +func submitAssessmentSignal( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, + cookie *http.Cookie, + csrf, key, body, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + path := "/api/v1/me/assessment-attempts/" + attemptID.String() + "/signals" + return assessmentAttemptHTTPRequest(t, harness, http.MethodPost, path, body, + sessionHTTPTestOrigin, cookie.Value, csrf, key, remoteAddr) +} + +func assertSignalReceipt(t *testing.T, response *httptest.ResponseRecorder, status int, receiptStatus string, accepted int) { + t.Helper() + var receipt struct { + Status string `json:"status"` + AcceptedEvents int `json:"accepted_events"` + ReceivedAt time.Time `json:"received_at"` + } + if response.Code != status || json.Unmarshal(response.Body.Bytes(), &receipt) != nil || + receipt.Status != receiptStatus || receipt.AcceptedEvents != accepted || receipt.ReceivedAt.IsZero() { + t.Fatalf("signal receipt = %d %s, want %d/%s/%d", response.Code, response.Body.String(), status, receiptStatus, accepted) + } +} + +func assertSignalStoredCounts( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, + wantEvents, wantBatches, wantOutcomes int64, +) { + t.Helper() + for _, check := range []struct { + table string + want int64 + }{ + {table: "assessment_signal_events", want: wantEvents}, + {table: "assessment_signal_batches", want: wantBatches}, + {table: "assessment_signal_idempotency_outcomes", want: wantOutcomes}, + } { + var got int64 + query := "SELECT count(*) FROM " + check.table + " WHERE attempt_id = $1" + if err := harness.pool.QueryRow(ctx, query, attemptID).Scan(&got); err != nil { + t.Fatalf("count %s: %v", check.table, err) + } + if got != check.want { + t.Fatalf("%s rows = %d, want %d", check.table, got, check.want) + } + } +} + +func assertAssessmentSignalMeasurementChecks(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID, itemID uuid.UUID) { + t.Helper() + for index, kind := range []string{"focus_loss", "copy"} { + batchID := uuid.New() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin measurement check %d: %v", index, err) + } + if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) + VALUES ($1, $2, clock_timestamp(), 1)`, batchID, attemptID); err != nil { + t.Fatalf("insert measurement boundary batch: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO assessment_signal_events ( + batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes + ) VALUES ($1, $2, 1, $3, $4, clock_timestamp(), NULL, NULL)`, batchID, attemptID, itemID, kind) + assertPgError(t, "reject null measurement for "+kind, err, "23514", "assessment_signal_events_measurement") + if err := tx.Rollback(ctx); err != nil { + t.Fatalf("rollback measurement check %d: %v", index, err) + } + } +} + +func assertAssessmentSignalImmutability(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + var batchID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_signal_batches + WHERE attempt_id = $1 ORDER BY received_at, id LIMIT 1`, attemptID).Scan(&batchID); err != nil { + t.Fatalf("read signal batch for immutability checks: %v", err) + } + _, err := pool.Exec(ctx, "UPDATE assessment_signal_batches SET event_count = event_count WHERE id = $1", batchID) + assertPgError(t, "reject signal batch update", err, "23000", "assessment_signal_batches_immutable") + _, err = pool.Exec(ctx, "DELETE FROM assessment_signal_batches WHERE id = $1", batchID) + assertPgError(t, "reject direct signal batch deletion", err, "23000", "assessment_signal_batches_immutable") + var ordinal int32 + if err := pool.QueryRow(ctx, `SELECT ordinal FROM assessment_signal_events + WHERE batch_id = $1 ORDER BY ordinal LIMIT 1`, batchID).Scan(&ordinal); err != nil { + t.Fatalf("read signal event for immutability checks: %v", err) + } + _, err = pool.Exec(ctx, "UPDATE assessment_signal_events SET occurred_at = occurred_at WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal) + assertPgError(t, "reject signal event update", err, "23000", "assessment_signal_events_immutable") + _, err = pool.Exec(ctx, "DELETE FROM assessment_signal_events WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal) + assertPgError(t, "reject direct signal event deletion", err, "23000", "assessment_signal_events_immutable") + + var scopeHash []byte + if err := pool.QueryRow(ctx, `SELECT scope_hash FROM assessment_signal_idempotency_outcomes + WHERE attempt_id = $1 ORDER BY received_at LIMIT 1`, attemptID).Scan(&scopeHash); err != nil { + t.Fatalf("read signal outcome for immutability check: %v", err) + } + _, err = pool.Exec(ctx, "UPDATE assessment_signal_idempotency_outcomes SET status = status WHERE scope_hash = $1", scopeHash) + assertPgError(t, "reject signal outcome update", err, "23000", "assessment_signal_idempotency_outcomes_immutable") +} + +func seedAssessmentSignalCapacity( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + attemptID, itemID uuid.UUID, + wantTotal int64, +) { + t.Helper() + var existing int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_events WHERE attempt_id = $1", attemptID).Scan(&existing); err != nil { + t.Fatalf("read signal count before capacity fixture: %v", err) + } + remaining := wantTotal - existing + if remaining <= 0 { + t.Fatalf("capacity fixture has no remaining rows: existing=%d target=%d", existing, wantTotal) + } + batchCount := int((remaining + 49) / 50) + batchIDs := make([]uuid.UUID, batchCount) + for index := range batchIDs { + batchIDs[index] = uuid.New() + } + tx, err := pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + t.Fatalf("begin bounded capacity fixture: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events DISABLE TRIGGER assessment_signal_event_guard"); err != nil { + t.Fatalf("disable only the capacity backstop for isolated fixture: %v", err) + } + if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) + SELECT batch.batch_id, $1, clock_timestamp(), LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer + FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)`, attemptID, batchIDs, remaining); err != nil { + t.Fatalf("insert bounded signal capacity batches: %v", err) + } + if _, err := tx.Exec(ctx, `WITH batches AS ( + SELECT batch.batch_id, LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer AS event_count + FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality) + ) + INSERT INTO assessment_signal_events ( + batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes + ) + SELECT batches.batch_id, $1, event.ordinality::integer, $4, 'fullscreen_exit', clock_timestamp(), NULL, NULL + FROM batches + CROSS JOIN LATERAL generate_series(1, batches.event_count) AS event(ordinality)`, attemptID, batchIDs, remaining, itemID); err != nil { + t.Fatalf("insert bounded signal capacity events: %v", err) + } + if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events ENABLE TRIGGER assessment_signal_event_guard"); err != nil { + t.Fatalf("restore signal capacity trigger: %v", err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit isolated signal capacity fixture: %v", err) + } +} + +func signalOutcomeCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 { + t.Helper() + var count int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_idempotency_outcomes WHERE attempt_id = $1", attemptID).Scan(&count); err != nil { + t.Fatalf("count signal receipts: %v", err) + } + return count +} diff --git a/backend/integration_test/candidate_card_access_migration_test.go b/backend/integration_test/candidate_card_access_migration_test.go new file mode 100644 index 0000000..3efd9b2 --- /dev/null +++ b/backend/integration_test/candidate_card_access_migration_test.go @@ -0,0 +1,115 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +const candidateCardAccessMigrationVersion = 30 + +func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackToCandidateCardAccessVersion(ctx, t, migrator) + + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, + } + candidate := identity.createUser(t, "candidate@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + organizationFixture := organizationFixture{ + ctx: ctx, pool: pool, identity: identity, + transactor: postgresadapter.NewTransactor(pool), now: now, + } + owner := organizationFixture.employer(t, "owner@example.com") + organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now) + if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events ( + id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at + ) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`, + uuid.New(), candidate.ID, organization.ID(), owner.ID, now); err != nil { + t.Fatalf("insert retained card access event: %v", err) + } + + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with retained card access history", err, privacyIntegrityViolation, "candidate_card_access_events_retained") + + var tableExists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass('public.candidate_card_access_events') IS NOT NULL`).Scan(&tableExists); err != nil { + t.Fatalf("check access history table after refused rollback: %v", err) + } + if !tableExists { + t.Fatal("candidate_card_access_events was removed despite retained history") + } + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1`, candidate.ID).Scan(&count); err != nil { + t.Fatalf("read retained access event after refused rollback: %v", err) + } + if count != 1 { + t.Fatalf("retained access event count = %d, want 1", count) + } + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() after refused rollback: %v", err) + } + version30Applied := false + for _, status := range statuses { + if status.Version == candidateCardAccessMigrationVersion { + version30Applied = status.Applied + break + } + } + if !version30Applied { + t.Fatal("migration 30 is not applied after its guarded Down() failed") + } +} + +func rollBackToCandidateCardAccessVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err) + } + version30Applied := false + laterMigrationApplied := false + for _, status := range statuses { + if !status.Applied { + continue + } + if status.Version == candidateCardAccessMigrationVersion { + version30Applied = true + } + if status.Version > candidateCardAccessMigrationVersion { + laterMigrationApplied = true + } + } + if !version30Applied { + t.Fatalf("migration %d is not applied", candidateCardAccessMigrationVersion) + } + if !laterMigrationApplied { + return + } + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err) + } + if result.Version <= candidateCardAccessMigrationVersion { + t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, candidateCardAccessMigrationVersion) + } + } +} diff --git a/backend/integration_test/candidate_privacy_http_test.go b/backend/integration_test/candidate_privacy_http_test.go new file mode 100644 index 0000000..10bffc6 --- /dev/null +++ b/backend/integration_test/candidate_privacy_http_test.go @@ -0,0 +1,549 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "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/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" +) + +const candidatePrivacyHTTPTestTimeout = 5 * time.Minute + +type candidatePrivacyHTTPHarness struct { + *sessionHTTPHarness + key domain.CandidateViewPseudonymKey + settings *candidateprivacy.Service +} + +func TestCandidatePrivacyHTTPReadsRecheckCurrentVisibility(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyHTTPTestTimeout) + defer cancel() + harness := newCandidatePrivacyHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, usersDependentTables...) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), harness.clock.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + + now := harness.clock.Now() + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + organizations := organizationFixture{ + ctx: ctx, pool: harness.pool, identity: identity, + transactor: postgresadapter.NewTransactor(harness.pool), now: now, + } + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, + organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, now: now} + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-target@example.test", passwordHash, true) + candidates := []domain.User{candidate} + for index := 1; index < 5; index++ { + other := privacy.candidate(t, fmt.Sprintf("privacy-cohort-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, other) + candidates = append(candidates, other) + } + for _, member := range candidates { + input := domain.CandidateProfileInput{Stack: privacyCohortConfirmedItems("go")} + if member.ID == candidate.ID { + input.FullName = confirmedDecision("Private Candidate Name") + input.Email = confirmedDecision("private-card-email@example.test") + } + profiles.save(t, member.ID, input, 0) + if member.ID == candidate.ID { + continue + } + c2 := privacy.grant(t, member.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, member.ID, c2.ID(), 0, domain.CardFieldStack) + } + + employer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now) + organizationA := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization A"), now) + organizationB := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization B"), now) + organizationC := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization C"), now) + inactiveOrganization := organizations.create(t, employer, organizations.completeProfile(t, "Privacy inactive organization"), now) + organizations.setMembershipState(t, inactiveOrganization.ID(), employer.ID, domain.MembershipStateLeft) + foreignEmployer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-foreign-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreignOrganization := organizations.create(t, foreignEmployer, organizations.completeProfile(t, "Privacy foreign organization"), now) + + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.170:1234") + employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.171:1234") + initialSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.172:1234") + if initialSettings.Code != http.StatusOK || initialSettings.Header().Get("Cache-Control") != "no-store" || + !strings.Contains(initialSettings.Body.String(), `"state":"closed"`) || !strings.Contains(initialSettings.Body.String(), `"closed_reason":"never_published"`) { + t.Fatalf("initial privacy settings = %d Cache-Control=%q %s", initialSettings.Code, initialSettings.Header().Get("Cache-Control"), initialSettings.Body.String()) + } + c2Grant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF, + "c2", privacyC2Version, sessionHTTPTestOrigin) + if c2Grant.Code != http.StatusOK { + t.Fatalf("C2 grant = %d %s", c2Grant.Code, c2Grant.Body.String()) + } + publication := harness.request(t, http.MethodPut, "/api/v1/me/privacy/publication", + `{"expected_version":0,"state":"published","fields":["stack"]}`, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.173:1234") + if publication.Code != http.StatusOK || publication.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("publication = %d Cache-Control=%q %s", publication.Code, publication.Header().Get("Cache-Control"), publication.Body.String()) + } + + aliasA, err := harness.key.ForOrganization(organizationA.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(A) error = %v", err) + } + aliasB, err := harness.key.ForOrganization(organizationB.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(B) error = %v", err) + } + if aliasA == aliasB { + t.Fatalf("organization-scoped aliases unexpectedly match: %q", aliasA) + } + assertCandidatePrivacyContactPortFixture(t, ctx, harness, employer.ID, organizationA.ID(), candidate.ID, aliasA) + unknownOrganization := uuid.New() + for _, test := range []struct { + name string + organizationID uuid.UUID + wantStatus int + wantCode string + useCandidate bool + }{ + {name: "active employer membership", organizationID: organizationA.ID(), wantStatus: http.StatusOK}, + {name: "candidate account", organizationID: organizationA.ID(), wantStatus: http.StatusForbidden, wantCode: "forbidden", useCandidate: true}, + {name: "inactive membership", organizationID: inactiveOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"}, + {name: "foreign membership", organizationID: foreignOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"}, + {name: "unknown organization", organizationID: unknownOrganization, wantStatus: http.StatusNotFound, wantCode: "not_found"}, + } { + t.Run(test.name, func(t *testing.T) { + cookie := employerCookie.Value + if test.useCandidate { + cookie = candidateCookie.Value + } + response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, test.organizationID, aliasA, cookie) + if response.Code != test.wantStatus { + t.Fatalf("card response = %d %s, want %d", response.Code, response.Body.String(), test.wantStatus) + } + if test.wantCode != "" { + requireSessionProblem(t, response, test.wantStatus, test.wantCode) + } + if test.wantStatus == http.StatusOK { + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("card Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var card struct { + Pseudonym string `json:"pseudonym"` + Stack []string `json:"stack"` + } + if err := json.Unmarshal(response.Body.Bytes(), &card); err != nil || card.Pseudonym != aliasA || len(card.Stack) != 1 || card.Stack[0] != "go" { + t.Fatalf("anonymous card = %+v, %v; body=%s", card, err, response.Body.String()) + } + for _, privateValue := range []string{candidate.ID.String(), candidate.Email.Address(), "Private Candidate Name", "private-card-email@example.test"} { + if strings.Contains(response.Body.String(), privateValue) { + t.Errorf("anonymous card contains private value %q", privateValue) + } + } + } + }) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationA.ID(), []string{"stack"}) + + preview := harness.request(t, http.MethodGet, "/api/v1/me/privacy/preview", "", "", candidateCookie.Value, "", "192.0.2.174:1234") + if preview.Code != http.StatusOK || preview.Header().Get("Cache-Control") != "no-store" || + strings.Contains(preview.Body.String(), aliasA) || strings.Contains(preview.Body.String(), candidate.ID.String()) { + t.Fatalf("private preview = %d Cache-Control=%q %s", preview.Code, preview.Header().Get("Cache-Control"), preview.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + + hideA := harness.request(t, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(), + "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.175:1234") + if hideA.Code != http.StatusOK || hideA.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("hide organization A = %d Cache-Control=%q %s", hideA.Code, hideA.Header().Get("Cache-Control"), hideA.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after hiding A = %d %s, want generic 404", response.Code, response.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusOK { + t.Fatalf("card for B after hiding A = %d %s, want independent organization access", response.Code, response.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) + assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationB.ID(), []string{"stack"}) + unhideA := harness.request(t, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(), + "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.176:1234") + if unhideA.Code != http.StatusNoContent { + t.Fatalf("unhide organization A = %d %s, want 204", unhideA.Code, unhideA.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusOK { + t.Fatalf("card after unhiding A = %d %s, want restored visibility while C2 is active", response.Code, response.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 2) + directHidden, err := harness.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: candidate.ID, Limit: 20}) + if err != nil || len(directHidden.Items) != 0 || directHidden.HasMore { + t.Fatalf("direct hidden organization list = %+v, %v; want an empty page after unhide", directHidden, err) + } + hiddenList := harness.request(t, http.MethodGet, "/api/v1/me/privacy/hidden-organizations", "", "", candidateCookie.Value, "", "192.0.2.177:1234") + if hiddenList.Code != http.StatusOK || !strings.Contains(hiddenList.Body.String(), `"items":[]`) || hiddenList.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("hidden organizations after unhide = %d Cache-Control=%q %s", hiddenList.Code, hiddenList.Header().Get("Cache-Control"), hiddenList.Body.String()) + } + privacyHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/history", "", "", candidateCookie.Value, "", "192.0.2.178:1234") + if privacyHistory.Code != http.StatusOK || !strings.Contains(privacyHistory.Body.String(), "publication_opened") || + !strings.Contains(privacyHistory.Body.String(), "organization_hidden") || !strings.Contains(privacyHistory.Body.String(), "organization_unhidden") { + t.Fatalf("privacy history = %d %s", privacyHistory.Code, privacyHistory.Body.String()) + } + accessHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/access-history", "", "", candidateCookie.Value, "", "192.0.2.179:1234") + if accessHistory.Code != http.StatusOK || accessHistory.Header().Get("Cache-Control") != "no-store" || !strings.Contains(accessHistory.Body.String(), "Privacy organization A") || !strings.Contains(accessHistory.Body.String(), "Privacy organization B") { + t.Fatalf("card access history = %d Cache-Control=%q %s", accessHistory.Code, accessHistory.Header().Get("Cache-Control"), accessHistory.Body.String()) + } + + // Hold the candidate account row so the employer read reaches and waits on + // its FOR SHARE visibility lock. Commit the competing hide only after the + // lock wait is observed; a visibility recheck must reject the stale cohort. + lockTx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin visibility race transaction: %v", err) + } + defer func() { _ = lockTx.Rollback(context.Background()) }() + if _, err := lockTx.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR UPDATE`, candidate.ID); err != nil { + t.Fatalf("lock candidate row for visibility race: %v", err) + } + aliasC, err := harness.key.ForOrganization(organizationC.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(C) error = %v", err) + } + raceResult := make(chan *httptest.ResponseRecorder, 1) + go func() { + raceResult <- candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationC.ID(), aliasC, employerCookie.Value) + }() + monitor := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-monitor") + if waitEvent, waiting := waitForLockWait(ctx, monitor, "candidate-privacy-http"); !waiting || waitEvent == "" { + t.Fatalf("card read did not wait for candidate visibility lock, wait event %q", waitEvent) + } + if _, err := lockTx.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, organizationC.ID(), now.Add(time.Second)); err != nil { + t.Fatalf("commit concurrent candidate hide fixture: %v", err) + } + if err := lockTx.Commit(ctx); err != nil { + t.Fatalf("commit visibility race transaction: %v", err) + } + raceResponse := <-raceResult + if raceResponse.Code != http.StatusNotFound { + t.Fatalf("card read that waited behind a hide = %d %s, want generic 404", raceResponse.Code, raceResponse.Body.String()) + } + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0) + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0) + + revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.180:1234") + if revoke.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s, want 204", revoke.Code, revoke.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after C2 revoke = %d %s, want generic 404", response.Code, response.Body.String()) + } + regrant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF, + "c2", privacyC2Version, sessionHTTPTestOrigin) + if regrant.Code != http.StatusOK { + t.Fatalf("C2 regrant = %d %s", regrant.Code, regrant.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after C2 regrant without republication = %d %s, want generic 404", response.Code, response.Body.String()) + } + closedSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.181:1234") + if closedSettings.Code != http.StatusOK || !strings.Contains(closedSettings.Body.String(), `"state":"closed"`) { + t.Fatalf("settings after C2 revoke and regrant = %d %s, want closed publication", closedSettings.Code, closedSettings.Body.String()) + } + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) +} + +func newCandidatePrivacyHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *candidatePrivacyHTTPHarness { + t.Helper() + pool := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-http") + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentQueries := consent.NewQueryService(consentStore, clock.Now) + consentCommands := consent.NewService(transactor, clock.Now) + privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + quota := companyquota.NewService(clock.Now) + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now) + privacyViews, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: clock.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 { + t.Fatalf("candidateview.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + consentHandler := v1.NewConsentHandler(consentQueries, consentCommands) + privacyHandler := v1.NewPrivacyHandler(privacyViews, privacySettings, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &candidatePrivacyHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + key: key, settings: privacySettings, + } +} + +func candidatePrivacyCardRequest(t *testing.T, harness *sessionHTTPHarness, organizationID uuid.UUID, handle, cookie string) *httptest.ResponseRecorder { + t.Helper() + path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", organizationID, handle) + return harness.request(t, http.MethodGet, path, "", "", cookie, "", "192.0.2.190:1234") +} + +func assertPrivacyCardAccessCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed'`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count candidate card access events: %v", err) + } + if count != want { + t.Fatalf("card access event count = %d, want %d", count, want) + } +} + +func assertPrivacyCardViewQuotaCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count card-view quota usage: %v", err) + } + if count != want { + t.Fatalf("card-view quota usage count = %d, want %d", count, want) + } +} + +func assertPrivacyCardAccessFields(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want []string) { + t.Helper() + var fields []string + if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id LIMIT 1`, candidateID, organizationID).Scan(&fields); err != nil { + t.Fatalf("read card-view audit fields: %v", err) + } + if len(fields) != len(want) { + t.Fatalf("card-view audit fields = %v, want %v", fields, want) + } + for index := range fields { + if fields[index] != want[index] { + t.Fatalf("card-view audit fields = %v, want %v", fields, want) + } + } +} + +type candidatePrivacyContactGrantState uint8 + +const ( + candidatePrivacyContactGrantAbsent candidatePrivacyContactGrantState = iota + candidatePrivacyContactGrantActive + candidatePrivacyContactGrantRevoked +) + +type candidatePrivacyContactGrantFixture struct { + state candidatePrivacyContactGrantState + workflowAccepted bool + organizationID uuid.UUID + candidateID uuid.UUID + fields domain.ContactFieldSet +} + +func (fixture *candidatePrivacyContactGrantFixture) currentFields(organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) { + if fixture == nil || fixture.state != candidatePrivacyContactGrantActive || + fixture.organizationID != organizationID || fixture.candidateID != candidateID { + return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed + } + // Workflow acceptance is deliberately not used as authorization evidence. + return fixture.fields, nil +} + +type candidatePrivacyContactTransactor struct { + inner outbound.Transactor + fixture *candidatePrivacyContactGrantFixture +} + +func (transactor candidatePrivacyContactTransactor) WithinTransaction( + ctx context.Context, + fn func(context.Context, outbound.UnitOfWork) error, +) error { + return transactor.inner.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + view := candidatePrivacyContactView{ + PrivacyViewRepository: unit.PrivacyView(), + fixture: transactor.fixture, + } + return fn(ctx, candidatePrivacyContactUnit{UnitOfWork: unit, view: view}) + }) +} + +type candidatePrivacyContactUnit struct { + outbound.UnitOfWork + + view outbound.PrivacyViewRepository +} + +func (unit candidatePrivacyContactUnit) PrivacyView() outbound.PrivacyViewRepository { + return unit.view +} + +type candidatePrivacyContactView struct { + outbound.PrivacyViewRepository + fixture *candidatePrivacyContactGrantFixture +} + +func (view candidatePrivacyContactView) CurrentFields(_ context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) { + return view.fixture.currentFields(organizationID, candidateID) +} + +func assertCandidatePrivacyContactPortFixture( + t *testing.T, + ctx context.Context, + harness *candidatePrivacyHTTPHarness, + actorID, organizationID, candidateID uuid.UUID, + handle string, +) { + t.Helper() + fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail, domain.ContactFieldPhone) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + fixture := &candidatePrivacyContactGrantFixture{ + organizationID: organizationID, + candidateID: candidateID, + fields: fields, + } + transactor := candidatePrivacyContactTransactor{ + inner: postgresadapter.NewTransactor(harness.pool), + fixture: fixture, + } + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(harness.pool), harness.key, harness.clock.Now) + quota := companyquota.NewService(harness.clock.Now) + service, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: projector, PseudonymKey: harness.key, Clock: harness.clock.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 { + t.Fatalf("candidateview.NewService() error = %v", err) + } + + for _, test := range []struct { + name string + state candidatePrivacyContactGrantState + want bool + }{ + {name: "active grant returns selected fields", state: candidatePrivacyContactGrantActive, want: true}, + {name: "workflow acceptance without a grant stays closed", state: candidatePrivacyContactGrantAbsent}, + {name: "revoked grant stays closed", state: candidatePrivacyContactGrantRevoked}, + } { + t.Run(test.name, func(t *testing.T) { + fixture.state = test.state + fixture.workflowAccepted = true + got, err := service.CurrentContactFields(ctx, actorID, organizationID, handle) + if test.want { + if err != nil { + t.Fatalf("CurrentContactFields() error = %v", err) + } + gotFields := got.Fields() + wantFields := fields.Fields() + if len(gotFields) != len(wantFields) { + t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields) + } + for index := range wantFields { + if gotFields[index] != wantFields[index] { + t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields) + } + } + } else if !errors.Is(err, outbound.ErrContactAccessClosed) { + t.Fatalf("CurrentContactFields() error = %v, want closed contact access", err) + } + assertPrivacyContactAudit(t, ctx, harness.pool, candidateID, organizationID, test.want) + }) + } +} + +func assertPrivacyContactAudit(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, checkFields bool) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count contact-read audit events: %v", err) + } + if count != 1 { + t.Fatalf("contact-read audit count = %d, want one successful read and no records for denied reads", count) + } + if !checkFields { + return + } + var fields []string + if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&fields); err != nil { + t.Fatalf("read contact-read audit fields: %v", err) + } + if len(fields) != 2 || fields[0] != "email" || fields[1] != "phone" { + t.Fatalf("contact-read audit fields = %v, want [email phone]", fields) + } +} diff --git a/backend/integration_test/candidate_privacy_test.go b/backend/integration_test/candidate_privacy_test.go index 9f57433..c9e2cd4 100644 --- a/backend/integration_test/candidate_privacy_test.go +++ b/backend/integration_test/candidate_privacy_test.go @@ -36,11 +36,13 @@ var ( candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"} candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"} candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"} + candidateCardAccessEventsTable = pgx.Identifier{"candidate_card_access_events"} // candidatePrivacyTables reference users, organizations, and the consent // ledger, so every TRUNCATE of those names them through // usersDependentTables. candidatePrivacyTables = []pgx.Identifier{ - candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, candidateSearchStatusesTable, candidatePublicationsTable, + candidateCardAccessEventsTable, candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, + candidateSearchStatusesTable, candidatePublicationsTable, } ) @@ -772,6 +774,66 @@ func TestCandidatePrivacyStorage(t *testing.T) { }) } +func TestCandidateCardAccessEventRetentionAndActorAnonymization(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now}, + ledger: postgresadapter.NewConsentStore(pool), now: now, + } + truncateTables(ctx, t, pool, usersDependentTables...) + + candidate := fixture.candidate(t, "privacy-owner@example.test") + verifyPrivacyCohortCandidate(t, fixture, candidate) + organizationOwner := fixture.organizations.employer(t, "privacy-organization-owner@example.test") + organization := fixture.organizations.create(t, organizationOwner, + fixture.organizations.completeProfile(t, "Access history organization"), now) + actor := fixture.candidate(t, "privacy-viewer@example.test") + + access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: candidate.ID, OrganizationID: organization.ID(), ActorID: actor.ID, + Kind: domain.CandidateCardAccessCardViewed, OccurredAt: now, + }) + if err != nil { + t.Fatalf("NewCandidateCardAccess() error = %v", err) + } + queries := sqlc.New(pool) + if err := queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{ + ID: uuidParam(access.ID()), CandidateID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization.ID()), + ActorID: uuidParam(actor.ID), Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: timeParam(access.OccurredAt()), + }); err != nil { + t.Fatalf("InsertCandidateCardAccessEvent(pseudonym-only) error = %v", err) + } + + _, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET field_codes = ARRAY['location'] WHERE id = $1`, access.ID()) + assertPgError(t, "reject card access field update", err, privacyIntegrityViolation, "candidate_card_access_events_immutable") + _, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET actor_id = NULL WHERE id = $1`, access.ID()) + assertPgError(t, "reject direct card access actor anonymization", err, privacyIntegrityViolation, "candidate_card_access_events_immutable") + _, err = pool.Exec(ctx, `DELETE FROM candidate_card_access_events WHERE id = $1`, access.ID()) + assertPgError(t, "reject card access deletion", err, privacyIntegrityViolation, "candidate_card_access_events_retained") + + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, actor.ID); err != nil { + t.Fatalf("DELETE audit actor = %v", err) + } + var storedCandidate, storedOrganization uuid.UUID + var storedActor pgtype.UUID + var kind string + var fields []string + if err := pool.QueryRow(ctx, `SELECT candidate_id, organization_id, actor_id, kind, field_codes FROM candidate_card_access_events WHERE id = $1`, access.ID()). + Scan(&storedCandidate, &storedOrganization, &storedActor, &kind, &fields); err != nil { + t.Fatalf("read retained card access = %v", err) + } + if storedCandidate != candidate.ID || storedOrganization != organization.ID() || storedActor.Valid || + kind != string(domain.CandidateCardAccessCardViewed) || len(fields) != 0 { + t.Fatalf("retained access = candidate %s org %s actor %+v kind %s fields %v", storedCandidate, storedOrganization, storedActor, kind, fields) + } +} + func containsWord(column, word string) bool { for _, part := range splitIdentifier(column) { if part == word { diff --git a/backend/integration_test/need_http_test.go b/backend/integration_test/need_http_test.go new file mode 100644 index 0000000..760d812 --- /dev/null +++ b/backend/integration_test/need_http_test.go @@ -0,0 +1,446 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/organization" +) + +func TestOrganizationNeedOwnerWorkflowOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) + defer cancel() + harness := newNeedHTTPHarness(ctx, t, env) + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + owner := createOrganizationHTTPUser(ctx, t, harness, "need-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "need-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + recruiter := createOrganizationHTTPUser(ctx, t, harness, "need-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidate := createOrganizationHTTPUser(ctx, t, harness, "need-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + unverified := createOrganizationHTTPUser(ctx, t, harness, "need-unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass, + env.Config.AppPublicURL, "", "192.0.2.44:1234") + requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified") + + organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "need-http-company") + insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now) + basePath := "/api/v1/organizations/" + organizationID.String() + "/needs" + initialSource := `{"title":"Payments backend","source_text":"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."}` + createdResponses := parallelNeedRequests(t, harness, http.MethodPost, basePath, initialSource, + env.Config.AppPublicURL, ownerSession, "need-http-create-1", 2) + if createdResponses[0].Code != http.StatusCreated || createdResponses[1].Code != http.StatusCreated || + createdResponses[0].Header().Get("Cache-Control") != "no-store" || string(createdResponses[0].Body.Bytes()) != string(createdResponses[1].Body.Bytes()) { + t.Fatalf("concurrent need create responses = %d %s and %d %s, want the same 201 response", + createdResponses[0].Code, createdResponses[0].Body.String(), createdResponses[1].Code, createdResponses[1].Body.String()) + } + originalBody := append([]byte(nil), createdResponses[0].Body.Bytes()...) + created := decodeNeedHTTPResponse(t, originalBody) + if created.ID == uuid.Nil || created.Version != 1 || created.RequirementsVersion != 1 || created.Recommendations.Status != string(domain.NeedRecommendationsNotAvailable) { + t.Fatalf("created need identity or recommendation state = %+v", created) + } + if created.Requirements.Specialization.Status != string(domain.NeedValueExtracted) || + created.Requirements.Specialization.Source == nil || created.Requirements.Specialization.Source.Origin != string(domain.NeedValueExtractedFromText) || + created.Requirements.Grade.Status != string(domain.NeedValueUnknown) || created.Requirements.Grade.Value != nil { + t.Fatalf("source extraction invented or omitted a need value: %+v", created.Requirements) + } + gotSkills := make([]string, 0, len(created.Requirements.RequiredSkills)) + for _, skill := range created.Requirements.RequiredSkills { + if skill.Status == string(domain.NeedItemExtracted) && skill.Source.Origin == string(domain.NeedValueExtractedFromText) { + gotSkills = append(gotSkills, skill.Name) + } + } + if !equalNeedStrings(gotSkills, []string{"Go", "PostgreSQL", "Temporal"}) { + t.Fatalf("extracted required skills = %v, want Go, PostgreSQL, Temporal", gotSkills) + } + if len(created.Readiness.MissingFields) == 0 { + t.Fatal("incomplete source text need has no readiness questions") + } + needPath := basePath + "/" + created.ID.String() + + changedKeyBody := `{"title":"Different request"}` + changedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, changedKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-create-1") + requireSessionProblem(t, changedKey, http.StatusUnprocessableEntity, "idempotency_key_reused") + + invalidNUL := organizationHTTPRequest(t, harness, http.MethodPost, basePath, + `{"title":"Bad\u0000title"}`, env.Config.AppPublicURL, ownerSession, "need-http-invalid-nul") + requireSessionProblem(t, invalidNUL, http.StatusBadRequest, "validation_failed") + var invalidProblem struct { + Errors []struct { + Pointer string `json:"pointer"` + } `json:"errors"` + } + if err := json.Unmarshal(invalidNUL.Body.Bytes(), &invalidProblem); err != nil || len(invalidProblem.Errors) == 0 { + t.Fatalf("NUL validation body = %s, decode error %v", invalidNUL.Body.String(), err) + } + updated := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + `{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"}]}`, + env.Config.AppPublicURL, ownerSession, "") + if updated.Code != http.StatusOK { + t.Fatalf("confirm extracted skill = %d %s, want 200", updated.Code, updated.Body.String()) + } + confirmed := decodeNeedHTTPResponse(t, updated.Body.Bytes()) + if confirmed.Version != 2 || confirmed.RequirementsVersion != 2 || confirmed.Recommendations.Status != string(domain.NeedRecommendationsPending) || + len(confirmed.Requirements.RequiredSkills) != 1 || confirmed.Requirements.RequiredSkills[0].Name != "Go" || + confirmed.Requirements.RequiredSkills[0].Status != string(domain.NeedItemConfirmed) { + t.Fatalf("confirmed need state = %+v", confirmed) + } + currentRead := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", ownerSession, "") + if currentRead.Code != http.StatusOK || string(currentRead.Body.Bytes()) == string(originalBody) { + t.Fatalf("current need read = %d %s, want edited current version", currentRead.Code, currentRead.Body.String()) + } + immutableReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, initialSource, + env.Config.AppPublicURL, ownerSession, "need-http-create-1") + if immutableReplay.Code != http.StatusCreated || string(immutableReplay.Body.Bytes()) != string(originalBody) { + t.Fatalf("live create replay = %d %s, want the original 201 body %s", immutableReplay.Code, immutableReplay.Body.String(), originalBody) + } + + expiryKeyBody := `{"title":"Boundary need"}` + expiryKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if expiryKey.Code != http.StatusCreated { + t.Fatalf("create need for expiry boundary = %d %s, want 201", expiryKey.Code, expiryKey.Body.String()) + } + expiryOriginal := decodeNeedHTTPResponse(t, expiryKey.Body.Bytes()) + boundary := harness.clock.Now() + expired, err := harness.pool.Exec(ctx, + `UPDATE idempotency_records AS record + SET created_at = $1, expires_at = $2 + WHERE EXISTS ( + SELECT 1 FROM organization_need_creation_results AS result + WHERE result.scope_hash = record.scope_hash + AND result.snapshot #>> '{need,title}' = 'Boundary need' + )`, + boundary.Add(-outbound.IdempotencyRetention), boundary) + if err != nil { + t.Fatalf("expire need create key at exact 24-hour boundary: %v", err) + } + if expired.RowsAffected() != 1 { + t.Fatalf("expired need create rows = %d, want 1", expired.RowsAffected()) + } + reusedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if reusedKey.Code != http.StatusCreated { + t.Fatalf("create after exact 24-hour replay boundary = %d %s, want a new 201", reusedKey.Code, reusedKey.Body.String()) + } + replacement := decodeNeedHTTPResponse(t, reusedKey.Body.Bytes()) + if replacement.ID == expiryOriginal.ID || replacement.Version != 1 { + t.Fatalf("expired key reused old need snapshot: %+v", replacement) + } + expiredReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if expiredReplay.Code != http.StatusCreated || string(expiredReplay.Body.Bytes()) != string(reusedKey.Body.Bytes()) { + t.Fatalf("replay after expired-key reuse = %d %s, want exact replacement response %s", expiredReplay.Code, expiredReplay.Body.String(), reusedKey.Body.String()) + } + + identicalUpdates := parallelNeedRequests(t, harness, http.MethodPatch, needPath, + `{"expected_version":2,"title":"Platform engineer"}`, env.Config.AppPublicURL, ownerSession, "", 2) + for index, response := range identicalUpdates { + if response.Code != http.StatusOK { + t.Fatalf("identical concurrent update %d = %d %s, want 200", index, response.Code, response.Body.String()) + } + } + concurrentCurrent := decodeNeedHTTPResponse(t, identicalUpdates[0].Body.Bytes()) + if concurrentCurrent.Version != 3 || concurrentCurrent.Title != "Platform engineer" { + t.Fatalf("identical concurrent update result = version %d title %q, want version 3", concurrentCurrent.Version, concurrentCurrent.Title) + } + differentUpdates := parallelNeedRequestsWithBodies(t, harness, http.MethodPatch, needPath, + []string{`{"expected_version":3,"title":"Payments platform"}`, `{"expected_version":3,"title":"Cloud platform"}`}, + env.Config.AppPublicURL, ownerSession) + var winner needHTTPResponse + successes := 0 + conflicts := 0 + for index, response := range differentUpdates { + switch response.Code { + case http.StatusOK: + successes++ + winner = decodeNeedHTTPResponse(t, response.Body.Bytes()) + case http.StatusPreconditionFailed: + conflicts++ + default: + t.Fatalf("different concurrent update %d = %d %s, want 200 or 412", index, response.Code, response.Body.String()) + } + } + if successes != 1 || conflicts != 1 || winner.Version != 4 { + t.Fatalf("different concurrent updates had %d successes and %d conflicts; winner = %+v, want one version 4 success", successes, conflicts, winner) + } + + staleNoOp := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + fmt.Sprintf(`{"expected_version":3,"title":%q}`, winner.Title), env.Config.AppPublicURL, ownerSession, "") + if staleNoOp.Code != http.StatusOK || decodeNeedHTTPResponse(t, staleNoOp.Body.Bytes()).Version != 4 { + t.Fatalf("stale no-op update = %d %s, want current version 4", staleNoOp.Code, staleNoOp.Body.String()) + } + staleInvalid := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + `{"expected_version":3,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"go","status":"confirmed"}]}`, + env.Config.AppPublicURL, ownerSession, "") + requireSessionProblem(t, staleInvalid, http.StatusPreconditionFailed, "version_conflict") + + secondNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Second need"}`, + env.Config.AppPublicURL, ownerSession, "need-http-create-2") + thirdNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Third need"}`, + env.Config.AppPublicURL, ownerSession, "need-http-create-3") + if secondNeed.Code != http.StatusCreated || thirdNeed.Code != http.StatusCreated { + t.Fatalf("create needs for pagination = %d %s and %d %s, want 201", secondNeed.Code, secondNeed.Body.String(), thirdNeed.Code, thirdNeed.Body.String()) + } + firstPage := readNeedHTTPPage(t, harness, ownerSession, basePath+"?limit=1") + if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" { + t.Fatalf("first need page = %+v, want one item and cursor", firstPage) + } + secondPage := readNeedHTTPPage(t, harness, ownerSession, + basePath+"?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) + if len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil || + firstPage.Items[0].ID == secondPage.Items[0].ID { + t.Fatalf("second need page = %+v, want the next distinct item", secondPage) + } + + for _, test := range []struct { + name string + session organizationHTTPSession + want int + }{ + {name: "foreign owner", session: foreignSession, want: http.StatusNotFound}, + {name: "active recruiter", session: recruiterSession, want: http.StatusForbidden}, + {name: "candidate", session: candidateSession, want: http.StatusForbidden}, + } { + t.Run(test.name, func(t *testing.T) { + response := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", test.session, "") + if response.Code != test.want { + t.Fatalf("need read = %d %s, want %d", response.Code, response.Body.String(), test.want) + } + if strings.Contains(response.Body.String(), "Payments backend") || strings.Contains(response.Body.String(), "PostgreSQL") { + t.Fatalf("denied response contains need data: %s", response.Body.String()) + } + }) + } + var versionCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2", organizationID, created.ID).Scan(&versionCount); err != nil { + t.Fatalf("read immutable need history: %v", err) + } + if versionCount != 4 { + t.Fatalf("need history rows = %d, want 4", versionCount) + } +} + +type needHTTPResponse struct { + ID uuid.UUID `json:"id"` + Title string `json:"title"` + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + Requirements struct { + Specialization struct { + Status string `json:"status"` + Value *string `json:"value"` + Source *struct { + Origin string `json:"origin"` + } `json:"source"` + } `json:"specialization"` + Grade struct { + Status string `json:"status"` + Value *string `json:"value"` + } `json:"grade"` + RequiredSkills []struct { + Name string `json:"name"` + Status string `json:"status"` + Source struct { + Origin string `json:"origin"` + } `json:"source"` + } `json:"required_skills"` + } `json:"requirements"` + Readiness struct { + MissingFields []json.RawMessage `json:"missing_fields"` + } `json:"readiness"` + Recommendations struct { + Status string `json:"status"` + } `json:"recommendations"` +} + +func decodeNeedHTTPResponse(t *testing.T, encoded []byte) needHTTPResponse { + t.Helper() + var response needHTTPResponse + if err := json.Unmarshal(encoded, &response); err != nil { + t.Fatalf("decode need response: %v", err) + } + return response +} + +func equalNeedStrings(left, right []string) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +type needHTTPPage struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +func readNeedHTTPPage(t *testing.T, harness *sessionHTTPHarness, session organizationHTTPSession, path string) needHTTPPage { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "") + if response.Code != http.StatusOK { + t.Fatalf("list organization needs = %d %s, want 200", response.Code, response.Body.String()) + } + var page needHTTPPage + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode need list response: %v", err) + } + return page +} + +func parallelNeedRequests( + t *testing.T, + harness *sessionHTTPHarness, + method, path, body, origin string, + session organizationHTTPSession, + idempotencyKey string, + count int, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, count) + var group sync.WaitGroup + start := make(chan struct{}) + for index := range count { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, idempotencyKey) + }) + } + close(start) + group.Wait() + return responses +} + +func parallelNeedRequestsWithBodies( + t *testing.T, + harness *sessionHTTPHarness, + method, path string, + bodies []string, + origin string, + session organizationHTTPSession, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, len(bodies)) + var group sync.WaitGroup + start := make(chan struct{}) + for index, body := range bodies { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, "") + }) + } + close(start) + group.Wait() + return responses +} + +func newNeedHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(io.Discard, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + needHandler := v1.NewNeedHandler(needService) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func needHTTPPath(organizationID, needID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID) +} diff --git a/backend/integration_test/needs_test.go b/backend/integration_test/needs_test.go index 031b4cd..7913452 100644 --- a/backend/integration_test/needs_test.go +++ b/backend/integration_test/needs_test.go @@ -14,6 +14,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" @@ -310,13 +311,207 @@ func TestOrganizationNeedsStorage(t *testing.T) { largeID := uuid.New() body["id"] = largeID.String() body["requirements_version"] = 1 - body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotBytes+1) + body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotStorageBytes+1) oversized, err := json.Marshal(body) if err != nil { t.Fatalf("encode oversized storage snapshot: %v", err) } insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot") }) + + t.Run("maximum bounded need shape stays within JSONB representation headroom", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Большой профиль"), now) + maximum := maximumBoundedIntegrationNeed(t, organization.ID(), now.Add(time.Minute)) + compact, err := json.Marshal(maximum.Snapshot()) + if err != nil { + t.Fatalf("marshal maximum bounded need: %v", err) + } + if len(compact) > domain.MaxNeedSnapshotBytes { + t.Fatalf("maximum bounded need compact JSON = %d bytes, exceeds %d", len(compact), domain.MaxNeedSnapshotBytes) + } + if len(compact) < 64*1024 { + t.Fatalf("maximum bounded need compact JSON = %d bytes, want a substantial combined source and requirement payload", len(compact)) + } + fixture.createNeed(t, maximum) + var storedBytes int + if err := pool.QueryRow(ctx, ` + SELECT octet_length(snapshot::text) + FROM organization_need_versions + WHERE organization_id = $1 AND need_id = $2 AND version = 1 + `, organization.ID(), maximum.ID()).Scan(&storedBytes); err != nil { + t.Fatalf("measure maximum need JSONB text size: %v", err) + } + if storedBytes < len(compact) || storedBytes-len(compact) > domain.MaxNeedJSONBTextHeadroom || storedBytes > domain.MaxNeedSnapshotStorageBytes { + t.Fatalf("maximum need storage = %d bytes, compact=%d headroom=%d; want storage within the explicit JSONB margin", + storedBytes, len(compact), domain.MaxNeedJSONBTextHeadroom) + } + if _, err := fixture.getNeed(organization.ID(), maximum.ID()); err != nil { + t.Fatalf("restore maximum bounded need: %v", err) + } + }) +} + +func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations to rollback test database: %v", err) + } + pool := newPoolFor(ctx, t, databaseURL) + now := time.Now().UTC().Truncate(time.Microsecond) + fixture := organizationFixture{ + ctx: ctx, pool: pool, + identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, + transactor: postgresadapter.NewTransactor(pool), now: now, + } + scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize)) + fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize)) + if _, err := pool.Exec(ctx, ` + INSERT INTO idempotency_records (scope_hash, fingerprint, created_at, expires_at) + VALUES ($1, $2, $3, $4) + `, scope, fingerprint, now, now.Add(outbound.IdempotencyRetention)); err != nil { + t.Fatalf("insert live idempotency row: %v", err) + } + if _, err := pool.Exec(ctx, ` + INSERT INTO organization_need_creation_results (scope_hash, snapshot) + VALUES ($1, '{"need":{},"readiness":{},"recommendations":{}}'::jsonb) + `, scope); err != nil { + t.Fatalf("insert live creation result: %v", err) + } + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("DownOne() succeeded while a need creation replay remained live") + } + assertNeedResultMigrationPresent(ctx, t, pool, 1) + + if _, err := pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2 WHERE scope_hash = $3", + now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil { + t.Fatalf("expire idempotency replay before checking historical bounds: %v", err) + } + owner := fixture.employer(t, "need-migration-owner@example.test") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now) + need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute)) + encoded, err := json.Marshal(need.Snapshot()) + if err != nil { + t.Fatalf("marshal rollback snapshot: %v", err) + } + var body map[string]any + if err := json.Unmarshal(encoded, &body); err != nil { + t.Fatalf("decode rollback snapshot: %v", err) + } + body["rollback_bound_fixture"] = strings.Repeat("p", 265000) + encoded, err = json.Marshal(body) + if err != nil { + t.Fatalf("encode rollback-bound snapshot: %v", err) + } + var storageSize int + if err := pool.QueryRow(ctx, "SELECT octet_length($1::jsonb::text)", encoded).Scan(&storageSize); err != nil { + t.Fatalf("measure rollback-bound snapshot: %v", err) + } + if storageSize <= domain.MaxNeedSnapshotBytes || storageSize > domain.MaxNeedSnapshotStorageBytes { + t.Fatalf("rollback fixture JSONB size = %d, want (%d, %d]", storageSize, domain.MaxNeedSnapshotBytes, domain.MaxNeedSnapshotStorageBytes) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin oversized-history fixture transaction: %v", err) + } + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at) + VALUES ($1, $2, 1, 1, $3, $3) + `, need.ID(), organization.ID(), now.Add(time.Minute)); err != nil { + t.Fatalf("insert oversized-history need parent: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot) + VALUES ($1, $2, 1, $3::jsonb) + `, organization.ID(), need.ID(), encoded); err != nil { + t.Fatalf("insert snapshot within current storage bound: %v", err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit oversized-history fixture: %v", err) + } + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("DownOne() succeeded while retained need history exceeded the prior bound") + } + assertNeedResultMigrationPresent(ctx, t, pool, 1) +} + +func assertNeedResultMigrationPresent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, resultRows int64) { + t.Helper() + var tableExists bool + var rows int64 + if err := pool.QueryRow(ctx, ` + SELECT to_regclass('organization_need_creation_results') IS NOT NULL, + (SELECT count(*) FROM organization_need_creation_results) + `).Scan(&tableExists, &rows); err != nil { + t.Fatalf("inspect migration preflight after rollback attempt: %v", err) + } + if !tableExists || rows != resultRows { + t.Fatalf("migration rollback changed state: result table exists=%t rows=%d, want true/%d", tableExists, rows, resultRows) + } +} + +func maximumBoundedIntegrationNeed(t *testing.T, organizationID uuid.UUID, at time.Time) domain.Need { + t.Helper() + quote := strings.Repeat("q", 300) + extractedVersion := int64(1) + extractor := "need-rules.2026-10.1" + source := domain.NeedValueSource{ + Origin: domain.NeedValueExtractedFromText, Quote: "e, + ExtractedInVersion: &extractedVersion, ExtractionVersion: &extractor, + } + makeSkills := func(prefix string) []domain.NeedSkill { + skills := make([]domain.NeedSkill, 0, 30) + for index := range 30 { + name := fmt.Sprintf("%s-%02d-%s", prefix, index, strings.Repeat("s", 80)) + skills = append(skills, domain.NeedSkill{Name: name, Status: domain.NeedItemExtracted, Source: source}) + } + return skills + } + tasks := make([]domain.NeedTask, 0, 20) + for index := range 20 { + prefix := fmt.Sprintf("task-%02d-", index) + tasks = append(tasks, domain.NeedTask{ + Text: prefix + strings.Repeat("t", 290-len(prefix)), Status: domain.NeedItemExtracted, Source: source, + }) + } + rejected := make([]domain.NeedRejectedSuggestion, 0, domain.MaxNeedRejectedSuggestions) + for index := range domain.MaxNeedRejectedSuggestions { + rejected = append(rejected, domain.NeedRejectedSuggestion{ + Field: domain.NeedRejectedSkills, Value: fmt.Sprintf("rejected-%02d-%s", index, strings.Repeat("r", 280)), + }) + } + manual := &domain.NeedValueSource{Origin: domain.NeedValueManual} + formats := []domain.NeedWorkFormat{domain.NeedWorkFormatRemote, domain.NeedWorkFormatOffice, domain.NeedWorkFormatHybrid} + grade := domain.GradeSenior + specialization := domain.SpecializationBackend + domainName := strings.Repeat("d", 100) + location := strings.Repeat("l", 100) + formatValue := formats + salary := domain.NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"} + requirements := domain.NeedRequirements{ + Specialization: domain.NeedValue[domain.SpecializationCode]{Status: domain.NeedValueConfirmed, Value: &specialization, Source: manual}, + Grade: domain.NeedValue[domain.GradeCode]{Status: domain.NeedValueConfirmed, Value: &grade, Source: manual}, + RequiredSkills: makeSkills("required"), DesiredSkills: makeSkills("desired"), Tasks: tasks, + Domain: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &domainName, Source: manual}, + WorkFormats: domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueConfirmed, Value: &formatValue, Source: manual}, + Location: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &location, Source: manual}, + Salary: domain.NeedValue[domain.NeedSalaryRange]{Status: domain.NeedValueConfirmed, Value: &salary, Source: manual}, + } + need, err := domain.NewNeed(domain.NeedSnapshot{ + ID: uuid.New(), OrganizationID: organizationID, Title: strings.Repeat("n", 200), SourceText: needIntegrationPointer(strings.Repeat("s", 10000)), + Version: 1, RequirementsVersion: 1, Requirements: requirements, RejectedSuggestions: rejected, + CreatedAt: at, UpdatedAt: at, + }) + if err != nil { + t.Fatalf("NewNeed(maximum bounded shape) error = %v", err) + } + return need } func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) { diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index 0ee3313..4e20fde 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -39,17 +39,27 @@ var ( // organizationTables are emptied together: memberships reference both // users and organizations. Creation snapshots reference idempotency records. organizationTables = []pgx.Identifier{ + {"candidate_card_access_events"}, {"organization_need_versions"}, {"organization_needs"}, + {"organization_need_creation_results"}, {"company_invitation_quota_usage"}, {"company_card_view_quota_usage"}, organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable, } candidateQuestionnaireTables = []pgx.Identifier{ {"candidate_questionnaire_specializations"}, {"candidate_questionnaires"}, } + assessmentAttemptTables = []pgx.Identifier{ + {"assessment_attempt_results"}, + {"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"}, + {"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"}, + } + supportCaseTables = []pgx.Identifier{ + {"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"}, + } // usersDependentTables is every table that references users, directly or // through another table of the list. A TRUNCATE of users must name all of // them, so a migration that adds such a table adds it here. - usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables) + usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables) ) // organizationFixture works on the bootstrap database. The tables are diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index fefcc22..dabd49a 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -242,9 +242,13 @@ func TestPolicyVersions(t *testing.T) { SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}}, {name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}}, {name: "delete of every row", sql: `DELETE FROM policy_versions`}, - // Include referencing quota tables so PostgreSQL reaches the + // Include referencing tables so PostgreSQL reaches the // immutable-policy trigger instead of its foreign-key precheck. - {name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, company_card_view_quota_usage`}, + {name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, + company_card_view_quota_usage, assessment_training_bank_bindings, + assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items, + support_cases, support_case_events, assessment_signal_idempotency_outcomes, + assessment_signal_events, assessment_signal_batches, assessment_attempt_results`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) diff --git a/backend/integration_test/privacy_cohort_test.go b/backend/integration_test/privacy_cohort_test.go new file mode 100644 index 0000000..7ee9436 --- /dev/null +++ b/backend/integration_test/privacy_cohort_test.go @@ -0,0 +1,248 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/policy" + + "github.com/google/uuid" +) + +func TestOrganizationAnonymousCandidateProjectionHonorsC2AndHiding(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + policies := postgresadapter.NewPolicyStore(pool) + if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ + ctx: ctx, pool: pool, identity: identity, + transactor: postgresadapter.NewTransactor(pool), now: now, + }, + ledger: postgresadapter.NewConsentStore(pool), now: now, + } + truncateTables(ctx, t, pool, usersDependentTables...) + owner := fixture.organizations.employer(t, "owner@example.test") + organization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization"), now) + organizationB := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization B"), now) + profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now} + + visible := make([]uuid.UUID, 0, 5) + for index := range 5 { + candidate := fixture.candidate(t, fmt.Sprintf("visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, fixture, candidate) + consent := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Duration(index)*time.Second)) + fixture.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility, + ) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Private Name Marker"), + Email: confirmedDecision("private-contact-marker@example.test"), + Stack: privacyCohortConfirmedItems( + "go", "UniqueStackMarker", + ), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: "Private Employer Marker", Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private Summary Marker", + }), + SoftSkills: privacyCohortConfirmedItems("Private Soft Skill Marker"), + Location: confirmedDecision("Private Location Marker"), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{ + Amount: 180_000, TaxBasis: domain.ProfileTaxNet, + }), + }, 0) + if _, err := fixture.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + visible = append(visible, candidate.ID) + } + + hidden := fixture.candidate(t, "hidden@example.test") + verifyPrivacyCohortCandidate(t, fixture, hidden) + hiddenConsent := fixture.grant(t, hidden.ID, domain.ConsentPurposePublication, privacyC2Version, now) + fixture.publish(t, hidden.ID, hiddenConsent.ID(), 0, domain.CardFieldStack) + fixture.hide(t, hidden.ID, organization.ID(), now) + + revoked := fixture.candidate(t, "revoked@example.test") + verifyPrivacyCohortCandidate(t, fixture, revoked) + revokedConsent := fixture.grant(t, revoked.ID, domain.ConsentPurposePublication, privacyC2Version, now) + fixture.publish(t, revoked.ID, revokedConsent.ID(), 0, domain.CardFieldStack) + fixture.revokeC2(t, revoked.ID, now.Add(time.Minute)) + + reader := postgresadapter.NewPrivacyCohortStore(pool) + sources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources() error = %v", err) + } + if len(sources) != len(visible) { + t.Fatalf("visible sources = %d, want %d after excluding hidden and revoked candidates", len(sources), len(visible)) + } + sourcesB, err := reader.ListVisibleCandidateViewSources(ctx, organizationB.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(B) error = %v", err) + } + sourcesAAgain, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(A again) error = %v", err) + } + if len(sourcesB) != len(visible)+1 || len(sourcesAAgain) != len(visible) { + t.Fatalf("visible sources A/B/A = %d/%d/%d, want %d/6/%d with B still seeing the organization-hidden candidate", len(sources), len(sourcesB), len(sourcesAAgain), len(visible), len(visible)) + } + candidateID := sources[0].CandidateID() + if !privacyCohortHasSource(sourcesB, candidateID) || !privacyCohortHasSource(sourcesAAgain, candidateID) { + t.Fatal("the same candidate was not visible in repository reads A/B/A") + } + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("dedicated-anonymous-view-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + aliasA, err := key.ForOrganization(organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(A) error = %v", err) + } + aliasB, err := key.ForOrganization(organizationB.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(B) error = %v", err) + } + aliasAAgain, err := key.ForOrganization(organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(A again) error = %v", err) + } + if aliasA != aliasAAgain || aliasA == aliasB { + t.Fatalf("repository-backed A/B/A aliases = %q/%q/%q, want stable A and distinct B", aliasA, aliasB, aliasAAgain) + } + service := anonymousprofile.NewService(reader, key, func() time.Time { return now.Add(2 * time.Minute) }) + views, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible() error = %v", err) + } + if len(views) != 5 { + t.Fatalf("ListVisible() returned %d views, want the five-member cohort", len(views)) + } + if !privacyCohortHasViewAlias(views, aliasA) { + t.Fatal("organization A projection did not contain its stable candidate alias") + } + viewsB, err := service.ListVisible(ctx, organizationB.ID()) + if err != nil { + t.Fatalf("ListVisible(B) error = %v", err) + } + viewsAAgain, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(A again) error = %v", err) + } + if len(viewsB) != 5 || !privacyCohortHasViewAlias(viewsB, aliasB) || !privacyCohortHasViewAlias(viewsAAgain, aliasAAgain) { + t.Fatalf("service projection A/B/A = %d/%d/%d aliases present=%t/%t", len(views), len(viewsB), len(viewsAAgain), privacyCohortHasViewAlias(viewsB, aliasB), privacyCohortHasViewAlias(viewsAAgain, aliasAAgain)) + } + for _, view := range views { + if view.ExperienceBand == nil || *view.ExperienceBand != domain.CandidateExperienceBandThreeToSix { + t.Errorf("experience band = %v, want 3_6", view.ExperienceBand) + } + if len(view.Skills) != 1 || view.Skills[0] != domain.CandidateViewSkillGo { + t.Errorf("skills = %v, want only the recognized canonical value", view.Skills) + } + if len(view.WorkFormats) != 1 || view.WorkFormats[0] != domain.QuestionnaireWorkFormatRemote { + t.Errorf("work formats = %v, want explicitly selected remote", view.WorkFormats) + } + if len(view.Categories) != 0 || len(view.SelfAssessment) != 1 || view.SelfAssessment[0].DeclaredGrade == nil { + t.Errorf("confirmed categories and self-assessment were not kept separate: categories=%v self_assessment=%v", view.Categories, view.SelfAssessment) + } + if view.SalaryCompatibility != nil { + t.Errorf("salary compatibility = %v, want unknown without an approved computed result", view.SalaryCompatibility) + } + } + encoded, err := json.Marshal(views) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + for _, marker := range []string{ + "Private Name Marker", "private-contact-marker@example.test", "Private Employer Marker", + "Private Summary Marker", "Private Soft Skill Marker", "Private Location Marker", + "UniqueStackMarker", "180000", hidden.ID.String(), revoked.ID.String(), + } { + if strings.Contains(string(encoded), marker) { + t.Errorf("organization-facing cohort contains private marker %q", marker) + } + } + + fixture.hide(t, visible[0], organization.ID(), now.Add(3*time.Minute)) + fourSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(four) error = %v", err) + } + fourViews, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(four) error = %v", err) + } + if len(fourSources) != 4 || len(fourViews) != 0 { + t.Fatalf("cohort of four sources/views = %d/%d, want 4/0 after suppression", len(fourSources), len(fourViews)) + } + for index := 1; index < len(visible)-1; index++ { + fixture.hide(t, visible[index], organization.ID(), now.Add(time.Duration(index+3)*time.Minute)) + } + oneSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(one) error = %v", err) + } + oneViews, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(one) error = %v", err) + } + if len(oneSources) != 1 || len(oneViews) != 0 { + t.Fatalf("cohort of one source/view = %d/%d, want 1/0 after suppression", len(oneSources), len(oneViews)) + } +} + +func privacyCohortHasSource(sources []domain.CandidateViewSource, candidateID uuid.UUID) bool { + for _, source := range sources { + if source.CandidateID() == candidateID { + return true + } + } + return false +} + +func privacyCohortHasViewAlias(views []domain.AnonymousCandidateViewDTO, alias string) bool { + for _, view := range views { + if view.Pseudonym == alias { + return true + } + } + return false +} + +func verifyPrivacyCohortCandidate(t *testing.T, fixture candidatePrivacyFixture, candidate domain.User) { + t.Helper() + if _, err := fixture.identity.store.Users().MarkEmailVerified(fixture.ctx, candidate.ID, candidate.RegistrationVersion, fixture.now); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } +} + +func privacyCohortConfirmedItems[V comparable](values ...V) []domain.ProfileClaimInput[V] { + items := make([]domain.ProfileClaimInput[V], 0, len(values)) + for _, value := range values { + items = append(items, domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed}) + } + return items +} diff --git a/backend/integration_test/support_cases_test.go b/backend/integration_test/support_cases_test.go new file mode 100644 index 0000000..a04a90b --- /dev/null +++ b/backend/integration_test/support_cases_test.go @@ -0,0 +1,746 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/usecase/supportcase" +) + +const supportCaseHTTPTimeout = 5 * time.Minute + +type supportCaseHTTPHarness struct { + *sessionHTTPHarness + supportClock *testClock +} + +func TestSupportCasesOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-owner@example.test", passwordHash, true) + other := createSupportCaseHTTPEmployer(ctx, t, harness, "support-other@example.test", passwordHash) + ownerLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.231:1234") + otherLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.232:1234") + ownerCookie, ownerCSRF := supportCaseLoginCredentials(t, ownerLogin) + otherCookie, otherCSRF := supportCaseLoginCredentials(t, otherLogin) + + if got := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", "", "", "", "192.0.2.233:1234").Code; got != http.StatusUnauthorized { + t.Fatalf("guest list status = %d, want 401", got) + } + + createSupport := `{"type":"support","description":"The assessment is unavailable; please help with access."}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.234:1234") + if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("create support case = %d Cache-Control=%q: %s, want 201 no-store; server logs: %s", created.Code, + created.Header().Get("Cache-Control"), created.Body.String(), harness.logs.String()) + } + var createdBody supportCaseHTTPResponse + if err := json.Unmarshal(created.Body.Bytes(), &createdBody); err != nil { + t.Fatalf("decode created support case: %v", err) + } + if createdBody.ID == "" || createdBody.Number == "" || createdBody.Type != "support" || createdBody.Status != "submitted" || + createdBody.Description != "The assessment is unavailable; please help with access." || len(createdBody.History) != 1 || createdBody.History[0].Kind != "created" { + t.Fatalf("created support case = %+v", createdBody) + } + + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1234") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key replay = %d %s, want original 201 body %s", replay.Code, replay.Body.String(), created.Body.String()) + } + var supportCaseCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE id = $1::uuid", createdBody.ID).Scan(&supportCaseCount); err != nil { + t.Fatalf("count idempotent support case: %v", err) + } + if supportCaseCount != 1 { + t.Fatalf("same-key support create stored %d cases, want exactly one", supportCaseCount) + } + changedBody := `{"type":"support","description":"The assessment result is missing; please investigate."}` + changedReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", changedBody, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1236") + requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + assertSupportCaseCount(t, ctx, harness, owner.ID, 1) + csrfDenied := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, "", "support-csrf-denied", "192.0.2.235:1237") + requireSessionProblem(t, csrfDenied, http.StatusForbidden, "csrf_check_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + assertSupportCaseCount(t, ctx, harness, owner.ID, 1) + ownRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+createdBody.ID, + "", ownerCookie, "", "", "192.0.2.235:1235") + var ownReadBody supportCaseHTTPResponse + if ownRead.Code != http.StatusOK || ownRead.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(ownRead.Body.Bytes(), &ownReadBody) != nil || ownReadBody.ID != createdBody.ID || + ownReadBody.Number != createdBody.Number || ownReadBody.Status != "submitted" { + t.Fatalf("owner GET = %d Cache-Control=%q %s, want own submitted case %s", ownRead.Code, + ownRead.Header().Get("Cache-Control"), ownRead.Body.String(), createdBody.ID) + } + + manualBody := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}` + manual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-1", "192.0.2.236:1234") + if manual.Code != http.StatusCreated { + t.Fatalf("manual assessment request without C3 or an earlier attempt = %d %s, want 201", manual.Code, manual.Body.String()) + } + var manualCase supportCaseHTTPResponse + if err := json.Unmarshal(manual.Body.Bytes(), &manualCase); err != nil { + t.Fatalf("decode manual assessment request: %v", err) + } + if manualCase.Type != "manual_assessment" || manualCase.Status != "waiting_expert" || len(manualCase.History) != 2 || + manualCase.History[1].Kind != "status_changed" || manualCase.RubricVersion != nil || + manualCase.ResponseTarget.BusinessDays != 5 || manualCase.ResponseTarget.Kind != "operational_goal" { + t.Fatalf("manual assessment request = %+v, want expert queue, optional rubric, and five-day operational target", manualCase) + } + manualRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+manualCase.ID, + "", ownerCookie, "", "", "192.0.2.236:1235") + var manualReadBody supportCaseHTTPResponse + if manualRead.Code != http.StatusOK || json.Unmarshal(manualRead.Body.Bytes(), &manualReadBody) != nil || + manualReadBody.ID != manualCase.ID || manualReadBody.Status != "waiting_expert" || manualReadBody.RubricVersion != nil { + t.Fatalf("manual case GET = %d %s, want unchanged waiting_expert case without a rubric", manualRead.Code, manualRead.Body.String()) + } + var attemptCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil { + t.Fatalf("read assessment attempts: %v", err) + } + if attemptCount != 0 { + t.Fatalf("manual request unexpectedly has %d prior assessment attempts", attemptCount) + } + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 4) + duplicateManual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1236") + requireSessionProblem(t, duplicateManual, http.StatusConflict, "state_conflict") + duplicateManualReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1237") + requireSessionProblem(t, duplicateManualReplay, http.StatusConflict, "state_conflict") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 6) + var openManualCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases + WHERE owner_id = $1 AND case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed')`, owner.ID). + Scan(&openManualCount); err != nil { + t.Fatalf("count open manual assessment cases: %v", err) + } + if openManualCount != 1 { + t.Fatalf("duplicate manual request created %d open cases, want one", openManualCount) + } + invalidDescription := `{"type":"support","description":"\u0085"}` + invalidDomain := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription, + ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1238") + requireSessionProblem(t, invalidDomain, http.StatusBadRequest, "validation_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 7) + invalidDomainRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription, + ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1239") + requireSessionProblem(t, invalidDomainRetry, http.StatusBadRequest, "validation_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 8) + var consentCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil { + t.Fatalf("read consent side effects: %v", err) + } + if consentCount != 0 { + t.Fatalf("manual assessment changed consent records to %d, want none", consentCount) + } + companyLimited := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + otherCookie, otherCSRF, "support-employer-manual", "192.0.2.236:1241") + requireSessionProblem(t, companyLimited, http.StatusForbidden, "forbidden") + requireSupportCaseRequestCount(t, ctx, harness, other.ID, 0) + resetSupportCaseRequestEvents(t, ctx, harness, owner.ID) + harness.supportClock.Advance(24 * time.Hour) + expiredKeyBody := `{"type":"support","description":"The original support key expired and was accepted again."}` + expiredKeyRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", expiredKeyBody, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.236:1240") + var expiredKeyCase supportCaseHTTPResponse + if expiredKeyRetry.Code != http.StatusCreated || json.Unmarshal(expiredKeyRetry.Body.Bytes(), &expiredKeyCase) != nil || + expiredKeyCase.ID == createdBody.ID || expiredKeyCase.Number == createdBody.Number || + expiredKeyCase.Description != "The original support key expired and was accepted again." { + t.Fatalf("same key at exact 24-hour expiry = %d %s, want a new 201 case", expiredKeyRetry.Code, expiredKeyRetry.Body.String()) + } + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 1) + + otherCase := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + otherCookie, otherCSRF, "support-other-1", "192.0.2.237:1234") + if otherCase.Code != http.StatusCreated { + t.Fatalf("other account create = %d %s, want 201", otherCase.Code, otherCase.Body.String()) + } + var otherCaseBody supportCaseHTTPResponse + if err := json.Unmarshal(otherCase.Body.Bytes(), &otherCaseBody); err != nil { + t.Fatalf("decode other account case: %v", err) + } + foreignReference := fmt.Sprintf(`{"type":"support","description":"Reference another account's case.","object":{"type":"support_case","id":%q}}`, otherCaseBody.ID) + foreign := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference, + ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.238:1234") + requireSessionProblem(t, foreign, http.StatusNotFound, "not_found") + foreignReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference, + ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.239:1234") + requireSessionProblem(t, foreignReplay, http.StatusNotFound, "not_found") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + foreignRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+otherCaseBody.ID, + "", ownerCookie, "", "", "192.0.2.240:1234") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + + list := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", ownerCookie, "", "", "192.0.2.241:1234") + if list.Code != http.StatusOK || list.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("list own cases = %d Cache-Control=%q: %s", list.Code, list.Header().Get("Cache-Control"), list.Body.String()) + } + var listBody struct { + Items []json.RawMessage `json:"items"` + } + if err := json.Unmarshal(list.Body.Bytes(), &listBody); err != nil { + t.Fatalf("decode own support case list: %v", err) + } + if len(listBody.Items) != 3 || strings.Contains(list.Body.String(), "The assessment is unavailable") || strings.Contains(list.Body.String(), "history") { + t.Fatalf("owner list leaked another case or full-case fields: %s", list.Body.String()) + } + pageOne := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases?limit=1", "", + ownerCookie, "", "", "192.0.2.241:1235") + var firstPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if pageOne.Code != http.StatusOK || json.Unmarshal(pageOne.Body.Bytes(), &firstPage) != nil || + len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" { + t.Fatalf("first support-case page = %d %s, want a cursor for more results", pageOne.Code, pageOne.Body.String()) + } + pageTwo := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", + ownerCookie, "", "", "192.0.2.241:1236") + var secondPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if pageTwo.Code != http.StatusOK || json.Unmarshal(pageTwo.Body.Bytes(), &secondPage) != nil || + len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil || + string(secondPage.Items[0]) == string(firstPage.Items[0]) { + t.Fatalf("second support-case page = %d %s, want one item and another page", pageTwo.Code, pageTwo.Body.String()) + } + pageThree := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*secondPage.Page.NextCursor), "", + ownerCookie, "", "", "192.0.2.241:1237") + var lastPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + } `json:"page"` + } + if pageThree.Code != http.StatusOK || json.Unmarshal(pageThree.Body.Bytes(), &lastPage) != nil || + len(lastPage.Items) != 1 || lastPage.Page.HasMore { + t.Fatalf("last support-case page = %d %s, want one item without another page", pageThree.Code, pageThree.Body.String()) + } + foreignCursor := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", + otherCookie, "", "", "192.0.2.241:1238") + requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed") + + resetSupportCaseRequestEvents(t, ctx, harness, owner.ID, other.ID) + for index := range 10 { + body := fmt.Sprintf(`{"type":"support","description":"Rate limit request %d."}`, index) + response := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + ownerCookie, ownerCSRF, fmt.Sprintf("support-limit-%d", index), fmt.Sprintf("192.0.2.%d:1234", 242+index)) + if response.Code != http.StatusCreated { + t.Fatalf("within-limit create %d = %d %s, want 201", index, response.Code, response.Body.String()) + } + } + overLimit := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", + `{"type":"support","description":"This request exceeds the account budget."}`, + ownerCookie, ownerCSRF, "support-limit-over", "192.0.2.247:1234") + if overLimit.Code != http.StatusTooManyRequests || overLimit.Header().Get("Retry-After") == "" { + t.Fatalf("eleventh owner create = %d Retry-After=%q %s, want 429 with a retry interval", overLimit.Code, overLimit.Header().Get("Retry-After"), overLimit.Body.String()) + } + assertRowCount(ctx, t, harness.pool, pgx.Identifier{"support_case_request_events"}, 10) +} + +func TestManualAssessmentPinsPublishedRubricAcrossReplayAndReopening(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + + firstPolicy, opening, bank, metadata := seedSupportManualRubric(ctx, t, harness) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-rubric-owner@example.test", passwordHash, true) + login := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, + sessionHTTPTestOrigin, "", "192.0.2.251:1234") + cookie, csrf := supportCaseLoginCredentials(t, login) + body := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1234") + var original supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &original) != nil || + original.RubricVersion == nil || *original.RubricVersion != firstPolicy.Version() || original.Status != "waiting_expert" { + t.Fatalf("manual request with a current reviewed rubric = %d %s, want 201 pinned to policy version %d", + created.Code, created.Body.String(), firstPolicy.Version()) + } + if strings.Contains(created.Body.String(), "rubric_opening_id") || strings.Contains(created.Body.String(), "rubric_policy_version_id") { + t.Fatalf("public response exposed private rubric pin columns: %s", created.Body.String()) + } + + assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID()) + var consentCount, attemptCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil { + t.Fatalf("read manual-assessment consent side effects: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil { + t.Fatalf("read manual-assessment attempt side effects: %v", err) + } + if consentCount != 0 || attemptCount != 0 { + t.Fatalf("manual request created %d consent records and %d attempts; want neither", consentCount, attemptCount) + } + read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID, + "", cookie, "", "", "192.0.2.252:1235") + var readBody supportCaseHTTPResponse + if read.Code != http.StatusOK || json.Unmarshal(read.Body.Bytes(), &readBody) != nil || + readBody.ID != original.ID || readBody.RubricVersion == nil || *readBody.RubricVersion != firstPolicy.Version() { + t.Fatalf("manual case GET = %d %s, want the original rubric version", read.Code, read.Body.String()) + } + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1236") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key manual replay = %d %s, want the immutable original response %s", replay.Code, replay.Body.String(), created.Body.String()) + } + + secondProductPolicy := domain.DemoProductPolicyV2() + secondProductPolicy.Assessment.MaxAttemptsPerWindow++ + secondPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.DemoPolicySeedAuthor, Policy: secondProductPolicy, + }) + if err != nil || secondPolicy.Version() <= firstPolicy.Version() { + t.Fatalf("publish later product policy = v%d, %v; want a later immutable version", secondPolicy.Version(), err) + } + harness.supportClock.now = secondPolicy.EffectiveAt() + secondOpening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: opening.Category, GradingPolicyID: secondPolicy.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }) + if err != nil || secondOpening.ID == opening.ID { + t.Fatalf("reopen category under later policy = %+v, %v; want a distinct current opening", secondOpening, err) + } + current, err := bank.CategoryAvailability(ctx, opening.Category) + if err != nil || current.ID != secondOpening.ID { + t.Fatalf("current category opening = %+v, %v; want the later opening", current, err) + } + + readAfterReopening := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID, + "", cookie, "", "", "192.0.2.252:1237") + replayAfterReopening := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1238") + var readAfterBody supportCaseHTTPResponse + if readAfterReopening.Code != http.StatusOK || json.Unmarshal(readAfterReopening.Body.Bytes(), &readAfterBody) != nil || + readAfterBody.RubricVersion == nil || *readAfterBody.RubricVersion != firstPolicy.Version() || + replayAfterReopening.Code != http.StatusCreated || replayAfterReopening.Body.String() != created.Body.String() { + t.Fatalf("old manual case changed after category reopening: GET=%d %s replay=%d %s", + readAfterReopening.Code, readAfterReopening.Body.String(), replayAfterReopening.Code, replayAfterReopening.Body.String()) + } + assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID()) +} + +func seedSupportManualRubric( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, +) (domain.PolicyVersion, domain.AssessmentCategoryOpening, *assessment.Bank, domain.AssessmentCategoryCatalogMetadata) { + t.Helper() + policyStore := postgresadapter.NewPolicyStore(harness.pool) + policyVersion, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, harness.supportClock.Now()) + if err != nil { + t.Fatalf("read current support policy for reviewed bank fixture: %v", err) + } + transactor := postgresadapter.NewTransactor(harness.pool) + bank := assessment.NewBank(transactor) + fixture := assessmentFixture{demoBundle: loadDemoBundleFile(t)} + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + bundle := fixture.reviewedBundle(int(required)) + bundle.Name = "support-case-manual-rubric" + bundle.Category = "support-case-manual-rubric" + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(support rubric fixture) error = %v", err) + } + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } + metadata, err := domain.NewAssessmentCategoryCatalogMetadata( + domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo}, + ) + if err != nil { + t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err) + } + category := domain.AssessmentCategory(bundle.Category) + opening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: category, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }) + if err != nil { + t.Fatalf("OpenCategory(support rubric fixture) error = %v", err) + } + return policyVersion, opening, bank, metadata +} + +func assertStoredSupportRubricPin( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + caseID string, + version int32, + openingID uuid.UUID, + policyID uuid.UUID, +) { + t.Helper() + var storedVersion int32 + var storedOpeningID, storedPolicyID uuid.UUID + err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id, rubric_policy_version_id + FROM support_cases WHERE id = $1::uuid`, caseID).Scan(&storedVersion, &storedOpeningID, &storedPolicyID) + if err != nil || storedVersion != version || storedOpeningID != openingID || storedPolicyID != policyID { + t.Fatalf("stored private rubric pin = v%d opening %s policy %s, %v; want v%d opening %s policy %s", + storedVersion, storedOpeningID, storedPolicyID, err, version, openingID, policyID) + } +} + +func TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + store := postgresadapter.NewIdentityStore(pool) + transactor := postgresadapter.NewTransactor(pool) + + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + passwordHash, err := identity.NewCredentials(hasher).HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + address, err := domain.NewEmailAddress("support-budget@example.test") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + registeredAt := time.Now().UTC().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioCandidate, RegisteredAt: registeredAt, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(user) error = %v", err) + } + if _, err := store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + + productPolicy := domain.DemoProductPolicyV2() + baseSupport := domain.DemoSupportPolicy() + limitedSupport, err := domain.NewSupportPolicy(domain.SupportPolicyInput{ + SupportResponseDays: baseSupport.SupportResponseDays(), ComplaintResponseDays: baseSupport.ComplaintResponseDays(), + ManualAssessmentResponseDays: baseSupport.ManualAssessmentResponseDays(), AppealResponseDays: baseSupport.AppealResponseDays(), + MaxRequestsPerWindow: 1, RequestWindow: time.Hour, MaxAppealsPerTarget: baseSupport.MaxAppealsPerTarget(), + PauseWhenWaitingForUser: baseSupport.PausesWhenWaitingForUser(), BusinessCalendarVersion: baseSupport.BusinessCalendarVersion(), + }) + if err != nil { + t.Fatalf("NewSupportPolicy() error = %v", err) + } + productPolicy.Support = &limitedSupport + policyClock := time.Now + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), policyClock).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: productPolicy, + }); err != nil { + t.Fatalf("publish budget test policy: %v", err) + } + + firstTimestamp := time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond) + var clockCalls atomic.Int32 + clock := func() time.Time { + if clockCalls.Add(1) == 1 { + return firstTimestamp + } + return firstTimestamp.Add(-time.Hour) + } + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock}) + if err != nil { + t.Fatalf("NewSupportCaseService() error = %v", err) + } + start := make(chan struct{}) + results := make(chan error, 2) + for index := range 2 { + go func(index int) { + <-start + _, err := service.Create(ctx, supportcase.CreateCommand{ + ActorID: user.ID, IdempotencyKey: fmt.Sprintf("support-budget-%d", index), + Type: domain.SupportCaseTypeSupport, Description: fmt.Sprintf("Budget request %d.", index), + }) + results <- err + }(index) + } + close(start) + firstError, secondError := <-results, <-results + if clockCalls.Load() != 2 { + t.Fatalf("service clock calls = %d, want one post-lock sample per request", clockCalls.Load()) + } + successes := 0 + limited := 0 + for _, err := range []error{firstError, secondError} { + switch { + case err == nil: + successes++ + case errors.Is(err, supportcase.ErrRateLimited): + limited++ + default: + t.Fatalf("concurrent request error = %v, want one create and one rate limit", err) + } + } + if successes != 1 || limited != 1 { + t.Fatalf("concurrent requests had %d creates and %d rate limits, want one each", successes, limited) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"support_cases"}, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"support_case_request_events"}, 1) +} + +func requireSupportCaseRequestCount( + t *testing.T, + ctx context.Context, + harness *supportCaseHTTPHarness, + ownerID uuid.UUID, + want int64, +) { + t.Helper() + var count int64 + if err := harness.pool.QueryRow(ctx, + "SELECT count(*) FROM support_case_request_events WHERE owner_id = $1", ownerID, + ).Scan(&count); err != nil { + t.Fatalf("count support request events for owner: %v", err) + } + if count != want { + t.Fatalf("support request events for owner = %d, want %d", count, want) + } +} + +func assertSupportCaseCount(t *testing.T, ctx context.Context, harness *supportCaseHTTPHarness, ownerID uuid.UUID, want int64) { + t.Helper() + var count int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE owner_id = $1", ownerID).Scan(&count); err != nil { + t.Fatalf("count support cases for owner: %v", err) + } + if count != want { + t.Fatalf("support cases for owner = %d, want %d", count, want) + } +} + +func resetSupportCaseRequestEvents( + t *testing.T, + ctx context.Context, + harness *supportCaseHTTPHarness, + ownerIDs ...uuid.UUID, +) { + t.Helper() + for _, ownerID := range ownerIDs { + if _, err := harness.pool.Exec(ctx, "DELETE FROM support_case_request_events WHERE owner_id = $1", ownerID); err != nil { + t.Fatalf("reset support request events for owner: %v", err) + } + } +} + +func createSupportCaseHTTPEmployer( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + registeredAt := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt, + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(employer) error = %v", err) + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + return user +} + +type supportCaseHTTPResponse struct { + ID string `json:"id"` + Number string `json:"number"` + Type string `json:"type"` + Status string `json:"status"` + Description string `json:"description"` + RubricVersion *int32 `json:"rubric_version"` + History []struct { + Kind string `json:"kind"` + } `json:"history"` + ResponseTarget struct { + Kind string `json:"kind"` + BusinessDays int32 `json:"business_days"` + } `json:"response_target"` +} + +func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *supportCaseHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + supportClock := &testClock{now: clock.Now()} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + publishedPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV2(), + }) + if err != nil { + t.Fatalf("publish explicit support demo policy: %v", err) + } + // Publication time comes from PostgreSQL and is later than the fixed + // session clock. Start support requests at the returned effective time. + supportClock.now = publishedPolicy.EffectiveAt() + service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: supportClock.Now}) + if err != nil { + t.Fatalf("NewSupportCaseService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + supportHandler := v1.NewSupportHandler(service) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &supportCaseHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + supportClock: supportClock, + } +} + +func supportCaseLoginCredentials(t *testing.T, response *httptest.ResponseRecorder) (string, string) { + t.Helper() + if response.Code != http.StatusCreated { + t.Fatalf("login support case account = %d %s, want 201", response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode support case login response: %v", err) + } + return cookie.Value, body.CSRFToken +} + +func supportCaseHTTP( + t *testing.T, + harness *supportCaseHTTPHarness, + method, path, body, cookie, csrf, idempotencyKey, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if method == http.MethodPost { + request.Header.Set("Origin", sessionHTTPTestOrigin) + request.Header.Set("Idempotency-Key", idempotencyKey) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + request.RemoteAddr = remoteAddr + response := httptest.NewRecorder() + harness.router.ServeHTTP(response, request) + return response +} diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 84ec4ff..564e1a1 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -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 ( diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index a594d8c..96fa5f7 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -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 diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 1bb34f1..ac39259 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -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() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index f486568..a65eb35 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -3,6 +3,7 @@ package api import ( + "lincodex/backend/internal/adapter/primary/http/apitypes" "math/bits" "strconv" "time" @@ -502,6 +503,10 @@ func (s *AnonymousCardContent) Encode(e *jx.Encoder) { // encodeFields encodes fields. func (s *AnonymousCardContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("pseudonym") + e.Str(s.Pseudonym) + } { e.FieldStart("categories") if s.Categories == nil { @@ -527,38 +532,47 @@ func (s *AnonymousCardContent) encodeFields(e *jx.Encoder) { } } { - e.FieldStart("experience_months") - s.ExperienceMonths.Encode(e) - } - { - e.FieldStart("soft_skills") - if s.SoftSkills == nil { + e.FieldStart("self_assessment") + if s.SelfAssessment == nil { e.Null() } else { e.ArrStart() - for _, elem := range s.SoftSkills { - e.Str(elem) + for _, elem := range s.SelfAssessment { + elem.Encode(e) } e.ArrEnd() } } { - e.FieldStart("location") - s.Location.Encode(e) + e.FieldStart("experience_band") + s.ExperienceBand.Encode(e) } { - e.FieldStart("relocation") - s.Relocation.Encode(e) + e.FieldStart("work_formats") + if s.WorkFormats == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range s.WorkFormats { + elem.Encode(e) + } + e.ArrEnd() + } + } + { + e.FieldStart("salary_compatibility") + s.SalaryCompatibility.Encode(e) } } -var jsonFieldsNameOfAnonymousCardContent = [6]string{ - 0: "categories", - 1: "stack", - 2: "experience_months", - 3: "soft_skills", - 4: "location", - 5: "relocation", +var jsonFieldsNameOfAnonymousCardContent = [7]string{ + 0: "pseudonym", + 1: "categories", + 2: "stack", + 3: "self_assessment", + 4: "experience_band", + 5: "work_formats", + 6: "salary_compatibility", } // Decode decodes AnonymousCardContent from json. @@ -570,8 +584,20 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { - case "categories": + case "pseudonym": requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Pseudonym = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pseudonym\"") + } + case "categories": + requiredBitSet[0] |= 1 << 1 if err := func() error { switch tt := d.Next(); tt { case jx.Null: @@ -596,7 +622,7 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"categories\"") } case "stack": - requiredBitSet[0] |= 1 << 1 + requiredBitSet[0] |= 1 << 2 if err := func() error { switch tt := d.Next(); tt { case jx.Null: @@ -604,9 +630,9 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { return err } default: - s.Stack = make([]StackTag, 0) + s.Stack = make([]AnonymousCardContentStackItem, 0) if err := d.Arr(func(d *jx.Decoder) error { - var elem StackTag + var elem AnonymousCardContentStackItem if err := elem.Decode(d); err != nil { return err } @@ -620,17 +646,7 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"stack\"") } - case "experience_months": - requiredBitSet[0] |= 1 << 2 - if err := func() error { - if err := s.ExperienceMonths.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"experience_months\"") - } - case "soft_skills": + case "self_assessment": requiredBitSet[0] |= 1 << 3 if err := func() error { switch tt := d.Next(); tt { @@ -639,15 +655,13 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { return err } default: - s.SoftSkills = make([]string, 0) + s.SelfAssessment = make([]CardSelfAssessment, 0) if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { + var elem CardSelfAssessment + if err := elem.Decode(d); err != nil { return err } - s.SoftSkills = append(s.SoftSkills, elem) + s.SelfAssessment = append(s.SelfAssessment, elem) return nil }); err != nil { return err @@ -655,27 +669,52 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { } return nil }(); err != nil { - return errors.Wrap(err, "decode field \"soft_skills\"") + return errors.Wrap(err, "decode field \"self_assessment\"") } - case "location": + case "experience_band": requiredBitSet[0] |= 1 << 4 if err := func() error { - if err := s.Location.Decode(d); err != nil { + if err := s.ExperienceBand.Decode(d); err != nil { return err } return nil }(); err != nil { - return errors.Wrap(err, "decode field \"location\"") + return errors.Wrap(err, "decode field \"experience_band\"") } - case "relocation": + case "work_formats": requiredBitSet[0] |= 1 << 5 if err := func() error { - if err := s.Relocation.Decode(d); err != nil { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + s.WorkFormats = make([]CandidateWorkFormat, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CandidateWorkFormat + if err := elem.Decode(d); err != nil { + return err + } + s.WorkFormats = append(s.WorkFormats, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_formats\"") + } + case "salary_compatibility": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.SalaryCompatibility.Decode(d); err != nil { return err } return nil }(); err != nil { - return errors.Wrap(err, "decode field \"relocation\"") + return errors.Wrap(err, "decode field \"salary_compatibility\"") } default: return errors.Errorf("unexpected field %q", k) @@ -687,7 +726,7 @@ func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00111111, + 0b01111111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -733,6 +772,50 @@ func (s *AnonymousCardContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AnonymousCardContentStackItem as json. +func (s AnonymousCardContentStackItem) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AnonymousCardContentStackItem from json. +func (s *AnonymousCardContentStackItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AnonymousCardContentStackItem to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AnonymousCardContentStackItem(v) { + case AnonymousCardContentStackItemGo: + *s = AnonymousCardContentStackItemGo + case AnonymousCardContentStackItemPostgresql: + *s = AnonymousCardContentStackItemPostgresql + case AnonymousCardContentStackItemKafka: + *s = AnonymousCardContentStackItemKafka + case AnonymousCardContentStackItemDocker: + *s = AnonymousCardContentStackItemDocker + default: + *s = AnonymousCardContentStackItem(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AnonymousCardContentStackItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AnonymousCardContentStackItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentAnswer as json. func (s AssessmentAnswer) Encode(e *jx.Encoder) { switch s.Type { @@ -840,11 +923,6 @@ func (s *AssessmentAnswer) Decode(d *jx.Decoder) error { found = true s.Type = match case "number": - // Type-based discrimination: check if field has expected JSON type - if typ := d.Next(); typ != jx.Number { - // Field exists but has wrong type, not a match for this variant - return d.Skip() - } match := NumberAnswerAssessmentAnswer if found && s.Type != match { s.Type = "" @@ -1887,6 +1965,189 @@ func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentClipboardSignal) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentClipboardSignal) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("size_bytes") + e.Int32(s.SizeBytes) + } +} + +var jsonFieldsNameOfAssessmentClipboardSignal = [4]string{ + 0: "kind", + 1: "item_instance_id", + 2: "occurred_at", + 3: "size_bytes", +} + +// Decode decodes AssessmentClipboardSignal from json. +func (s *AssessmentClipboardSignal) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentClipboardSignal to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "item_instance_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ItemInstanceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"item_instance_id\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + case "size_bytes": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.SizeBytes = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"size_bytes\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentClipboardSignal") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentClipboardSignal) { + name = jsonFieldsNameOfAssessmentClipboardSignal[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentClipboardSignal) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentClipboardSignal) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentClipboardSignalKind as json. +func (s AssessmentClipboardSignalKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentClipboardSignalKind from json. +func (s *AssessmentClipboardSignalKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentClipboardSignalKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentClipboardSignalKind(v) { + case AssessmentClipboardSignalKindCopy: + *s = AssessmentClipboardSignalKindCopy + case AssessmentClipboardSignalKindPaste: + *s = AssessmentClipboardSignalKindPaste + case AssessmentClipboardSignalKindCut: + *s = AssessmentClipboardSignalKindCut + default: + *s = AssessmentClipboardSignalKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentClipboardSignalKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentClipboardSignalKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentCorrectiveAttempt) Encode(e *jx.Encoder) { e.ObjStart() @@ -4518,6 +4779,642 @@ func (s *AssessmentFinalization) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentFinalizeConflictProblem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentFinalizeConflictProblem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(409) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } + { + if s.PendingItemIds != nil { + e.FieldStart("pending_item_ids") + e.ArrStart() + for _, elem := range s.PendingItemIds { + json.EncodeUUID(e, elem) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfAssessmentFinalizeConflictProblem = [9]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", + 8: "pending_item_ids", +} + +// Decode decodes AssessmentFinalizeConflictProblem from json. +func (s *AssessmentFinalizeConflictProblem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFinalizeConflictProblem to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + case "pending_item_ids": + if err := func() error { + s.PendingItemIds = make([]uuid.UUID, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem uuid.UUID + v, err := json.DecodeUUID(d) + elem = v + if err != nil { + return err + } + s.PendingItemIds = append(s.PendingItemIds, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pending_item_ids\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentFinalizeConflictProblem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b00001111, + 0b00000000, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentFinalizeConflictProblem) { + name = jsonFieldsNameOfAssessmentFinalizeConflictProblem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentFinalizeConflictProblem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFinalizeConflictProblem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentFinalizeConflictProblemCode as json. +func (s AssessmentFinalizeConflictProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentFinalizeConflictProblemCode from json. +func (s *AssessmentFinalizeConflictProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFinalizeConflictProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentFinalizeConflictProblemCode(v) { + case AssessmentFinalizeConflictProblemCodeStateConflict: + *s = AssessmentFinalizeConflictProblemCodeStateConflict + case AssessmentFinalizeConflictProblemCodeIdempotencyInProgress: + *s = AssessmentFinalizeConflictProblemCodeIdempotencyInProgress + default: + *s = AssessmentFinalizeConflictProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentFinalizeConflictProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFinalizeConflictProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentFocusLossSignal) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentFocusLossSignal) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("duration_ms") + e.Int32(s.DurationMs) + } +} + +var jsonFieldsNameOfAssessmentFocusLossSignal = [4]string{ + 0: "kind", + 1: "item_instance_id", + 2: "occurred_at", + 3: "duration_ms", +} + +// Decode decodes AssessmentFocusLossSignal from json. +func (s *AssessmentFocusLossSignal) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFocusLossSignal to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "item_instance_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ItemInstanceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"item_instance_id\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + case "duration_ms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Int32() + s.DurationMs = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"duration_ms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentFocusLossSignal") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentFocusLossSignal) { + name = jsonFieldsNameOfAssessmentFocusLossSignal[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentFocusLossSignal) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFocusLossSignal) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentFocusLossSignalKind as json. +func (s AssessmentFocusLossSignalKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentFocusLossSignalKind from json. +func (s *AssessmentFocusLossSignalKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFocusLossSignalKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentFocusLossSignalKind(v) { + case AssessmentFocusLossSignalKindFocusLoss: + *s = AssessmentFocusLossSignalKindFocusLoss + default: + *s = AssessmentFocusLossSignalKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentFocusLossSignalKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFocusLossSignalKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentFullscreenExitSignal) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentFullscreenExitSignal) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentFullscreenExitSignal = [3]string{ + 0: "kind", + 1: "item_instance_id", + 2: "occurred_at", +} + +// Decode decodes AssessmentFullscreenExitSignal from json. +func (s *AssessmentFullscreenExitSignal) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFullscreenExitSignal to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "item_instance_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ItemInstanceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"item_instance_id\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentFullscreenExitSignal") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentFullscreenExitSignal) { + name = jsonFieldsNameOfAssessmentFullscreenExitSignal[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentFullscreenExitSignal) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFullscreenExitSignal) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentFullscreenExitSignalKind as json. +func (s AssessmentFullscreenExitSignalKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentFullscreenExitSignalKind from json. +func (s *AssessmentFullscreenExitSignalKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentFullscreenExitSignalKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentFullscreenExitSignalKind(v) { + case AssessmentFullscreenExitSignalKindFullscreenExit: + *s = AssessmentFullscreenExitSignalKindFullscreenExit + default: + *s = AssessmentFullscreenExitSignalKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentFullscreenExitSignalKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentFullscreenExitSignalKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentGap) Encode(e *jx.Encoder) { e.ObjStart() @@ -7778,6 +8675,432 @@ func (s *AssessmentSessions) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentSignalBatch) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSignalBatch) encodeFields(e *jx.Encoder) { + { + e.FieldStart("events") + e.ArrStart() + for _, elem := range s.Events { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentSignalBatch = [1]string{ + 0: "events", +} + +// Decode decodes AssessmentSignalBatch from json. +func (s *AssessmentSignalBatch) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalBatch to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "events": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Events = make([]AssessmentSignalEvent, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentSignalEvent + if err := elem.Decode(d); err != nil { + return err + } + s.Events = append(s.Events, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"events\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSignalBatch") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSignalBatch) { + name = jsonFieldsNameOfAssessmentSignalBatch[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSignalBatch) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalBatch) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentSignalEvent as json. +func (s AssessmentSignalEvent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +func (s AssessmentSignalEvent) encodeFields(e *jx.Encoder) { + switch s.Type { + case AssessmentFocusLossSignalAssessmentSignalEvent: + e.FieldStart("kind") + e.Str("focus_loss") + { + s := s.AssessmentFocusLossSignal + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("duration_ms") + e.Int32(s.DurationMs) + } + } + case AssessmentSignalEventCopyAssessmentSignalEvent, AssessmentSignalEventCutAssessmentSignalEvent, AssessmentSignalEventPasteAssessmentSignalEvent: + switch s.Type { + case AssessmentSignalEventCopyAssessmentSignalEvent: + e.FieldStart("kind") + e.Str("copy") + case AssessmentSignalEventCutAssessmentSignalEvent: + e.FieldStart("kind") + e.Str("cut") + case AssessmentSignalEventPasteAssessmentSignalEvent: + e.FieldStart("kind") + e.Str("paste") + } + { + s := s.AssessmentClipboardSignal + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("size_bytes") + e.Int32(s.SizeBytes) + } + } + case AssessmentFullscreenExitSignalAssessmentSignalEvent: + e.FieldStart("kind") + e.Str("fullscreen_exit") + { + s := s.AssessmentFullscreenExitSignal + { + e.FieldStart("item_instance_id") + s.ItemInstanceID.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + } + } +} + +// Decode decodes AssessmentSignalEvent from json. +func (s *AssessmentSignalEvent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalEvent to nil") + } + // Sum type discriminator. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + if found { + return d.Skip() + } + switch string(key) { + case "kind": + typ, err := d.Str() + if err != nil { + return err + } + switch typ { + case "focus_loss": + s.Type = AssessmentFocusLossSignalAssessmentSignalEvent + found = true + case "copy": + s.Type = AssessmentSignalEventCopyAssessmentSignalEvent + found = true + case "cut": + s.Type = AssessmentSignalEventCutAssessmentSignalEvent + found = true + case "paste": + s.Type = AssessmentSignalEventPasteAssessmentSignalEvent + found = true + case "fullscreen_exit": + s.Type = AssessmentFullscreenExitSignalAssessmentSignalEvent + found = true + default: + return errors.Errorf("unknown type %s", typ) + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case AssessmentFocusLossSignalAssessmentSignalEvent: + if err := s.AssessmentFocusLossSignal.Decode(d); err != nil { + return err + } + case AssessmentSignalEventCopyAssessmentSignalEvent, AssessmentSignalEventCutAssessmentSignalEvent, AssessmentSignalEventPasteAssessmentSignalEvent: + if err := s.AssessmentClipboardSignal.Decode(d); err != nil { + return err + } + case AssessmentFullscreenExitSignalAssessmentSignalEvent: + if err := s.AssessmentFullscreenExitSignal.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentSignalEvent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalEvent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentSignalReceipt) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSignalReceipt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("accepted_events") + e.Int32(s.AcceptedEvents) + } + { + e.FieldStart("received_at") + s.ReceivedAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentSignalReceipt = [3]string{ + 0: "status", + 1: "accepted_events", + 2: "received_at", +} + +// Decode decodes AssessmentSignalReceipt from json. +func (s *AssessmentSignalReceipt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalReceipt to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "accepted_events": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.AcceptedEvents = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted_events\"") + } + case "received_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ReceivedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"received_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSignalReceipt") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSignalReceipt) { + name = jsonFieldsNameOfAssessmentSignalReceipt[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSignalReceipt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalReceipt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentSignalReceiptStatus as json. +func (s AssessmentSignalReceiptStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentSignalReceiptStatus from json. +func (s *AssessmentSignalReceiptStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalReceiptStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentSignalReceiptStatus(v) { + case AssessmentSignalReceiptStatusAccepted: + *s = AssessmentSignalReceiptStatusAccepted + case AssessmentSignalReceiptStatusSaturated: + *s = AssessmentSignalReceiptStatusSaturated + default: + *s = AssessmentSignalReceiptStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentSignalReceiptStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalReceiptStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentSpecializationAvailability) Encode(e *jx.Encoder) { e.ObjStart() @@ -8829,6 +10152,54 @@ func (s *CandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CandidateExperienceBand as json. +func (s CandidateExperienceBand) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CandidateExperienceBand from json. +func (s *CandidateExperienceBand) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateExperienceBand to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CandidateExperienceBand(v) { + case CandidateExperienceBand01: + *s = CandidateExperienceBand01 + case CandidateExperienceBand13: + *s = CandidateExperienceBand13 + case CandidateExperienceBand36: + *s = CandidateExperienceBand36 + case CandidateExperienceBand6Plus: + *s = CandidateExperienceBand6Plus + case CandidateExperienceBand03: + *s = CandidateExperienceBand03 + case CandidateExperienceBand3Plus: + *s = CandidateExperienceBand3Plus + default: + *s = CandidateExperienceBand(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CandidateExperienceBand) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateExperienceBand) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CandidateHandle as json. func (s CandidateHandle) Encode(e *jx.Encoder) { unwrapped := string(s) @@ -10654,6 +12025,88 @@ func (s *CandidateQuestionnaireUpdate) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CandidateSalaryCompatibility as json. +func (s CandidateSalaryCompatibility) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CandidateSalaryCompatibility from json. +func (s *CandidateSalaryCompatibility) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateSalaryCompatibility to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CandidateSalaryCompatibility(v) { + case CandidateSalaryCompatibilityCompatible: + *s = CandidateSalaryCompatibilityCompatible + case CandidateSalaryCompatibilityNotCompatible: + *s = CandidateSalaryCompatibilityNotCompatible + default: + *s = CandidateSalaryCompatibility(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CandidateSalaryCompatibility) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateSalaryCompatibility) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CandidateWorkFormat as json. +func (s CandidateWorkFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CandidateWorkFormat from json. +func (s *CandidateWorkFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateWorkFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CandidateWorkFormat(v) { + case CandidateWorkFormatRemote: + *s = CandidateWorkFormatRemote + case CandidateWorkFormatOffice: + *s = CandidateWorkFormatOffice + case CandidateWorkFormatHybrid: + *s = CandidateWorkFormatHybrid + default: + *s = CandidateWorkFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CandidateWorkFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateWorkFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CardAccess) Encode(e *jx.Encoder) { e.ObjStart() @@ -10973,11 +12426,16 @@ func (s *CardCategory) encodeFields(e *jx.Encoder) { e.FieldStart("grade") s.Grade.Encode(e) } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } } -var jsonFieldsNameOfCardCategory = [2]string{ +var jsonFieldsNameOfCardCategory = [3]string{ 0: "specialization", 1: "grade", + 2: "strength", } // Decode decodes CardCategory from json. @@ -11009,6 +12467,16 @@ func (s *CardCategory) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"grade\"") } + case "strength": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Strength.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"strength\"") + } default: return errors.Errorf("unexpected field %q", k) } @@ -11019,7 +12487,7 @@ func (s *CardCategory) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000011, + 0b00000111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -11065,6 +12533,46 @@ func (s *CardCategory) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CardCategoryStrength as json. +func (s CardCategoryStrength) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CardCategoryStrength from json. +func (s *CardCategoryStrength) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardCategoryStrength to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CardCategoryStrength(v) { + case CardCategoryStrengthStandard: + *s = CardCategoryStrengthStandard + case CardCategoryStrengthStrong: + *s = CardCategoryStrengthStrong + default: + *s = CardCategoryStrength(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CardCategoryStrength) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardCategoryStrength) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CardField as json. func (s CardField) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -11083,6 +12591,10 @@ func (s *CardField) Decode(d *jx.Decoder) error { switch CardField(v) { case CardFieldCategories: *s = CardFieldCategories + case CardFieldSalaryCompatibility: + *s = CardFieldSalaryCompatibility + case CardFieldSelfAssessment: + *s = CardFieldSelfAssessment case CardFieldStack: *s = CardFieldStack case CardFieldExperience: @@ -11093,6 +12605,8 @@ func (s *CardField) Decode(d *jx.Decoder) error { *s = CardFieldLocation case CardFieldRelocation: *s = CardFieldRelocation + case CardFieldWorkFormats: + *s = CardFieldWorkFormats default: *s = CardField(v) } @@ -11317,6 +12831,172 @@ func (s *CardPreview) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *CardSelfAssessment) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CardSelfAssessment) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("confirmation_status") + s.ConfirmationStatus.Encode(e) + } + { + if s.DeclaredGrade.Set { + e.FieldStart("declared_grade") + s.DeclaredGrade.Encode(e) + } + } +} + +var jsonFieldsNameOfCardSelfAssessment = [3]string{ + 0: "specialization", + 1: "confirmation_status", + 2: "declared_grade", +} + +// Decode decodes CardSelfAssessment from json. +func (s *CardSelfAssessment) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardSelfAssessment to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "confirmation_status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ConfirmationStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmation_status\"") + } + case "declared_grade": + if err := func() error { + s.DeclaredGrade.Reset() + if err := s.DeclaredGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"declared_grade\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CardSelfAssessment") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCardSelfAssessment) { + name = jsonFieldsNameOfCardSelfAssessment[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CardSelfAssessment) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardSelfAssessment) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CardSelfAssessmentConfirmationStatus as json. +func (s CardSelfAssessmentConfirmationStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CardSelfAssessmentConfirmationStatus from json. +func (s *CardSelfAssessmentConfirmationStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardSelfAssessmentConfirmationStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CardSelfAssessmentConfirmationStatus(v) { + case CardSelfAssessmentConfirmationStatusConfirmed: + *s = CardSelfAssessmentConfirmationStatusConfirmed + case CardSelfAssessmentConfirmationStatusUnconfirmed: + *s = CardSelfAssessmentConfirmationStatusUnconfirmed + default: + *s = CardSelfAssessmentConfirmationStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CardSelfAssessmentConfirmationStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardSelfAssessmentConfirmationStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CatalogDirection) Encode(e *jx.Encoder) { e.ObjStart() @@ -16763,44 +18443,6 @@ func (s *FinalizeMyAssessmentAttemptBadRequest) UnmarshalJSON(data []byte) error return s.Decode(d) } -// Encode encodes FinalizeMyAssessmentAttemptConflict as json. -func (s *FinalizeMyAssessmentAttemptConflict) Encode(e *jx.Encoder) { - unwrapped := (*Problem)(s) - - unwrapped.Encode(e) -} - -// Decode decodes FinalizeMyAssessmentAttemptConflict from json. -func (s *FinalizeMyAssessmentAttemptConflict) Decode(d *jx.Decoder) error { - if s == nil { - return errors.New("invalid: unable to decode FinalizeMyAssessmentAttemptConflict to nil") - } - var unwrapped Problem - if err := func() error { - if err := unwrapped.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "alias") - } - *s = FinalizeMyAssessmentAttemptConflict(unwrapped) - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s *FinalizeMyAssessmentAttemptConflict) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *FinalizeMyAssessmentAttemptConflict) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - // Encode encodes FinalizeMyAssessmentAttemptForbidden as json. func (s *FinalizeMyAssessmentAttemptForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -18369,6 +20011,158 @@ func (s *GetOrganizationBadRequest) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetOrganizationCandidateCardBadRequest as json. +func (s *GetOrganizationCandidateCardBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationCandidateCardBadRequest from json. +func (s *GetOrganizationCandidateCardBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationCandidateCardBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationCandidateCardBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationCandidateCardBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationCandidateCardBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationCandidateCardForbidden as json. +func (s *GetOrganizationCandidateCardForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationCandidateCardForbidden from json. +func (s *GetOrganizationCandidateCardForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationCandidateCardForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationCandidateCardForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationCandidateCardForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationCandidateCardForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationCandidateCardNotFound as json. +func (s *GetOrganizationCandidateCardNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationCandidateCardNotFound from json. +func (s *GetOrganizationCandidateCardNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationCandidateCardNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationCandidateCardNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationCandidateCardNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationCandidateCardNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationCandidateCardUnauthorized as json. +func (s *GetOrganizationCandidateCardUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationCandidateCardUnauthorized from json. +func (s *GetOrganizationCandidateCardUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationCandidateCardUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationCandidateCardUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationCandidateCardUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationCandidateCardUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetOrganizationForbidden as json. func (s *GetOrganizationForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -29756,6 +31550,94 @@ func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CandidateExperienceBand as json. +func (o NilCandidateExperienceBand) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes CandidateExperienceBand from json. +func (o *NilCandidateExperienceBand) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilCandidateExperienceBand to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v CandidateExperienceBand + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilCandidateExperienceBand) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilCandidateExperienceBand) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CandidateSalaryCompatibility as json. +func (o NilCandidateSalaryCompatibility) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes CandidateSalaryCompatibility from json. +func (o *NilCandidateSalaryCompatibility) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilCandidateSalaryCompatibility to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v CandidateSalaryCompatibility + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilCandidateSalaryCompatibility) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilCandidateSalaryCompatibility) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConsentOrganization as json. func (o NilConsentOrganization) Encode(e *jx.Encoder) { if o.Null { @@ -30286,52 +32168,6 @@ func (s *NilGradeCode) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes int as json. -func (o NilInt) Encode(e *jx.Encoder) { - if o.Null { - e.Null() - return - } - e.Int(int(o.Value)) -} - -// Decode decodes int from json. -func (o *NilInt) Decode(d *jx.Decoder) error { - if o == nil { - return errors.New("invalid: unable to decode NilInt to nil") - } - if d.Next() == jx.Null { - if err := d.Null(); err != nil { - return err - } - - var v int - o.Value = v - o.Null = true - return nil - } - o.Null = false - v, err := d.Int() - if err != nil { - return err - } - o.Value = int(v) - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s NilInt) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *NilInt) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - // Encode encodes int32 as json. func (o NilInt32) Encode(e *jx.Encoder) { if o.Null { @@ -32553,7 +34389,7 @@ func (s *NumberAnswer) encodeFields(e *jx.Encoder) { } { e.FieldStart("number") - e.Float64(s.Number) + json.EncodeJSON(e, s.Number) } } @@ -32584,8 +34420,8 @@ func (s *NumberAnswer) Decode(d *jx.Decoder) error { case "number": requiredBitSet[0] |= 1 << 1 if err := func() error { - v, err := d.Float64() - s.Number = float64(v) + v, err := json.DecodeJSON[apitypes.AssessmentNumber](d) + s.Number = v if err != nil { return err } @@ -32981,6 +34817,55 @@ func (s *OptNeedTitle) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GradeCode as json. +func (o OptNilGradeCode) Encode(e *jx.Encoder) { + if !o.Set { + return + } + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes GradeCode from json. +func (o *OptNilGradeCode) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptNilGradeCode to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v GradeCode + o.Value = v + o.Set = true + o.Null = true + return nil + } + o.Set = true + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptNilGradeCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptNilGradeCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes InvitationDeclineComment as json. func (o OptNilInvitationDeclineComment) Encode(e *jx.Encoder) { if !o.Set { @@ -44408,6 +46293,272 @@ func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) UnmarshalJSON(dat return s.Decode(d) } +// Encode encodes RecordMyAssessmentAttemptSignalsBadRequest as json. +func (s *RecordMyAssessmentAttemptSignalsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsBadRequest from json. +func (s *RecordMyAssessmentAttemptSignalsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsConflict as json. +func (s *RecordMyAssessmentAttemptSignalsConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsConflict from json. +func (s *RecordMyAssessmentAttemptSignalsConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsForbidden as json. +func (s *RecordMyAssessmentAttemptSignalsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsForbidden from json. +func (s *RecordMyAssessmentAttemptSignalsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsNotFound as json. +func (s *RecordMyAssessmentAttemptSignalsNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsNotFound from json. +func (s *RecordMyAssessmentAttemptSignalsNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsRequestEntityTooLarge as json. +func (s *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsRequestEntityTooLarge from json. +func (s *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsRequestEntityTooLarge to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsRequestEntityTooLarge(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsUnauthorized as json. +func (s *RecordMyAssessmentAttemptSignalsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsUnauthorized from json. +func (s *RecordMyAssessmentAttemptSignalsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RecordMyAssessmentAttemptSignalsUnprocessableEntity as json. +func (s *RecordMyAssessmentAttemptSignalsUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RecordMyAssessmentAttemptSignalsUnprocessableEntity from json. +func (s *RecordMyAssessmentAttemptSignalsUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RecordMyAssessmentAttemptSignalsUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RecordMyAssessmentAttemptSignalsUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RecordMyAssessmentAttemptSignalsUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RecordMyAssessmentAttemptSignalsUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes RegisterAccountBadRequest as json. func (s *RegisterAccountBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 3a1d9eb..964567f 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -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" diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 7048758..b6b01b4 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -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 diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 15a305d..a68a30b 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -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, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 10baad2..d60f6fe 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -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: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index dc00c38..cc666c2 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -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" { diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index beba8da..ad342d5 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -4,6 +4,7 @@ package api import ( "fmt" + "lincodex/backend/internal/adapter/primary/http/apitypes" "time" "github.com/go-faster/errors" @@ -190,33 +191,37 @@ func (s *AccountScenario) UnmarshalText(data []byte) error { } } -// The anonymous candidate card as an organization reads it. Only values that the candidate confirmed -// reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a -// soft skill, the location) that looks like a contact (an email address, a phone number, a URL or -// domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no -// name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of -// the private profile or of a contact disclosure is reachable from it; a contact reaches an -// organization only through the contact grant of an accepted invitation. Each property is null when +// The anonymous candidate card as an organization reads it. Only explicitly published values reach it; +// unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It +// carries no name, contact, resume text, employer, salary figure, account or profile identifier, and +// no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches +// an organization only through the contact grant of an accepted invitation. Each property is null when // its field is not published or the candidate has no value for it, so the card does not tell the two // apart. The set of properties is closed, and an organization-visible card must never gain a property // that identifies the candidate. The search ranking and the full card of an organization's search // result are defined by the search contract, which reuses this content. // Ref: #/components/schemas/AnonymousCardContent type AnonymousCardContent struct { + // Stable opaque alias scoped to the reading organization. It is not an account or profile identifier + // and changes across organizations. + Pseudonym string `json:"pseudonym"` // Categories confirmed by assessment results, or null. Categories []CardCategory `json:"categories"` - // Technology tags of the candidate, or null. - Stack []StackTag `json:"stack"` - // Total months of work experience, summed by the server without the employers, periods, or - // descriptions, or null. - ExperienceMonths NilInt `json:"experience_months"` - // Soft skills of the candidate, or null. - SoftSkills []string `json:"soft_skills"` - // City or region as free text, never a street address, or null. Plain text; clients show it as text, - // never as HTML. - Location NilString `json:"location"` - // Whether the candidate is ready to relocate, or null. - Relocation NilBool `json:"relocation"` + // Recognized confirmed technology codes only, or null. + Stack []AnonymousCardContentStackItem `json:"stack"` + // Candidate-declared specialization and grade, separate from categories. + SelfAssessment []CardSelfAssessment `json:"self_assessment"` + // Coarse total work-experience bucket, or null. + ExperienceBand NilCandidateExperienceBand `json:"experience_band"` + // Explicitly opted-in work formats, or null. + WorkFormats []CandidateWorkFormat `json:"work_formats"` + // Nullable compatibility result with no salary values. + SalaryCompatibility NilCandidateSalaryCompatibility `json:"salary_compatibility"` +} + +// GetPseudonym returns the value of Pseudonym. +func (s *AnonymousCardContent) GetPseudonym() string { + return s.Pseudonym } // GetCategories returns the value of Categories. @@ -225,28 +230,33 @@ func (s *AnonymousCardContent) GetCategories() []CardCategory { } // GetStack returns the value of Stack. -func (s *AnonymousCardContent) GetStack() []StackTag { +func (s *AnonymousCardContent) GetStack() []AnonymousCardContentStackItem { return s.Stack } -// GetExperienceMonths returns the value of ExperienceMonths. -func (s *AnonymousCardContent) GetExperienceMonths() NilInt { - return s.ExperienceMonths +// GetSelfAssessment returns the value of SelfAssessment. +func (s *AnonymousCardContent) GetSelfAssessment() []CardSelfAssessment { + return s.SelfAssessment } -// GetSoftSkills returns the value of SoftSkills. -func (s *AnonymousCardContent) GetSoftSkills() []string { - return s.SoftSkills +// GetExperienceBand returns the value of ExperienceBand. +func (s *AnonymousCardContent) GetExperienceBand() NilCandidateExperienceBand { + return s.ExperienceBand } -// GetLocation returns the value of Location. -func (s *AnonymousCardContent) GetLocation() NilString { - return s.Location +// GetWorkFormats returns the value of WorkFormats. +func (s *AnonymousCardContent) GetWorkFormats() []CandidateWorkFormat { + return s.WorkFormats } -// GetRelocation returns the value of Relocation. -func (s *AnonymousCardContent) GetRelocation() NilBool { - return s.Relocation +// GetSalaryCompatibility returns the value of SalaryCompatibility. +func (s *AnonymousCardContent) GetSalaryCompatibility() NilCandidateSalaryCompatibility { + return s.SalaryCompatibility +} + +// SetPseudonym sets the value of Pseudonym. +func (s *AnonymousCardContent) SetPseudonym(val string) { + s.Pseudonym = val } // SetCategories sets the value of Categories. @@ -255,28 +265,111 @@ func (s *AnonymousCardContent) SetCategories(val []CardCategory) { } // SetStack sets the value of Stack. -func (s *AnonymousCardContent) SetStack(val []StackTag) { +func (s *AnonymousCardContent) SetStack(val []AnonymousCardContentStackItem) { s.Stack = val } -// SetExperienceMonths sets the value of ExperienceMonths. -func (s *AnonymousCardContent) SetExperienceMonths(val NilInt) { - s.ExperienceMonths = val +// SetSelfAssessment sets the value of SelfAssessment. +func (s *AnonymousCardContent) SetSelfAssessment(val []CardSelfAssessment) { + s.SelfAssessment = val } -// SetSoftSkills sets the value of SoftSkills. -func (s *AnonymousCardContent) SetSoftSkills(val []string) { - s.SoftSkills = val +// SetExperienceBand sets the value of ExperienceBand. +func (s *AnonymousCardContent) SetExperienceBand(val NilCandidateExperienceBand) { + s.ExperienceBand = val } -// SetLocation sets the value of Location. -func (s *AnonymousCardContent) SetLocation(val NilString) { - s.Location = val +// SetWorkFormats sets the value of WorkFormats. +func (s *AnonymousCardContent) SetWorkFormats(val []CandidateWorkFormat) { + s.WorkFormats = val } -// SetRelocation sets the value of Relocation. -func (s *AnonymousCardContent) SetRelocation(val NilBool) { - s.Relocation = val +// SetSalaryCompatibility sets the value of SalaryCompatibility. +func (s *AnonymousCardContent) SetSalaryCompatibility(val NilCandidateSalaryCompatibility) { + s.SalaryCompatibility = val +} + +// AnonymousCardContentHeaders wraps AnonymousCardContent with response headers. +type AnonymousCardContentHeaders struct { + CacheControl CacheControlNoStore + Response AnonymousCardContent +} + +// GetCacheControl returns the value of CacheControl. +func (s *AnonymousCardContentHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AnonymousCardContentHeaders) GetResponse() AnonymousCardContent { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AnonymousCardContentHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AnonymousCardContentHeaders) SetResponse(val AnonymousCardContent) { + s.Response = val +} + +func (*AnonymousCardContentHeaders) getOrganizationCandidateCardRes() {} + +type AnonymousCardContentStackItem string + +const ( + AnonymousCardContentStackItemGo AnonymousCardContentStackItem = "go" + AnonymousCardContentStackItemPostgresql AnonymousCardContentStackItem = "postgresql" + AnonymousCardContentStackItemKafka AnonymousCardContentStackItem = "kafka" + AnonymousCardContentStackItemDocker AnonymousCardContentStackItem = "docker" +) + +// AllValues returns all AnonymousCardContentStackItem values. +func (AnonymousCardContentStackItem) AllValues() []AnonymousCardContentStackItem { + return []AnonymousCardContentStackItem{ + AnonymousCardContentStackItemGo, + AnonymousCardContentStackItemPostgresql, + AnonymousCardContentStackItemKafka, + AnonymousCardContentStackItemDocker, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AnonymousCardContentStackItem) MarshalText() ([]byte, error) { + switch s { + case AnonymousCardContentStackItemGo: + return []byte(s), nil + case AnonymousCardContentStackItemPostgresql: + return []byte(s), nil + case AnonymousCardContentStackItemKafka: + return []byte(s), nil + case AnonymousCardContentStackItemDocker: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AnonymousCardContentStackItem) UnmarshalText(data []byte) error { + switch AnonymousCardContentStackItem(data) { + case AnonymousCardContentStackItemGo: + *s = AnonymousCardContentStackItemGo + return nil + case AnonymousCardContentStackItemPostgresql: + *s = AnonymousCardContentStackItemPostgresql + return nil + case AnonymousCardContentStackItemKafka: + *s = AnonymousCardContentStackItemKafka + return nil + case AnonymousCardContentStackItemDocker: + *s = AnonymousCardContentStackItemDocker + return nil + default: + return errors.Errorf("invalid value: %q", data) + } } // Candidate answer, selected by `format`, which must equal the format of the answered item. It carries @@ -928,6 +1021,103 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability) func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {} +// Ref: #/components/schemas/AssessmentClipboardSignal +type AssessmentClipboardSignal struct { + Kind AssessmentClipboardSignalKind `json:"kind"` + ItemInstanceID AssessmentItemId `json:"item_instance_id"` + OccurredAt Timestamp `json:"occurred_at"` + // Byte count only. Clipboard or selection contents are not transmitted or retained. + SizeBytes int32 `json:"size_bytes"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentClipboardSignal) GetKind() AssessmentClipboardSignalKind { + return s.Kind +} + +// GetItemInstanceID returns the value of ItemInstanceID. +func (s *AssessmentClipboardSignal) GetItemInstanceID() AssessmentItemId { + return s.ItemInstanceID +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *AssessmentClipboardSignal) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// GetSizeBytes returns the value of SizeBytes. +func (s *AssessmentClipboardSignal) GetSizeBytes() int32 { + return s.SizeBytes +} + +// SetKind sets the value of Kind. +func (s *AssessmentClipboardSignal) SetKind(val AssessmentClipboardSignalKind) { + s.Kind = val +} + +// SetItemInstanceID sets the value of ItemInstanceID. +func (s *AssessmentClipboardSignal) SetItemInstanceID(val AssessmentItemId) { + s.ItemInstanceID = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *AssessmentClipboardSignal) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +// SetSizeBytes sets the value of SizeBytes. +func (s *AssessmentClipboardSignal) SetSizeBytes(val int32) { + s.SizeBytes = val +} + +type AssessmentClipboardSignalKind string + +const ( + AssessmentClipboardSignalKindCopy AssessmentClipboardSignalKind = "copy" + AssessmentClipboardSignalKindPaste AssessmentClipboardSignalKind = "paste" + AssessmentClipboardSignalKindCut AssessmentClipboardSignalKind = "cut" +) + +// AllValues returns all AssessmentClipboardSignalKind values. +func (AssessmentClipboardSignalKind) AllValues() []AssessmentClipboardSignalKind { + return []AssessmentClipboardSignalKind{ + AssessmentClipboardSignalKindCopy, + AssessmentClipboardSignalKindPaste, + AssessmentClipboardSignalKindCut, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentClipboardSignalKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentClipboardSignalKindCopy: + return []byte(s), nil + case AssessmentClipboardSignalKindPaste: + return []byte(s), nil + case AssessmentClipboardSignalKindCut: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentClipboardSignalKind) UnmarshalText(data []byte) error { + switch AssessmentClipboardSignalKind(data) { + case AssessmentClipboardSignalKindCopy: + *s = AssessmentClipboardSignalKindCopy + return nil + case AssessmentClipboardSignalKindPaste: + *s = AssessmentClipboardSignalKindPaste + return nil + case AssessmentClipboardSignalKindCut: + *s = AssessmentClipboardSignalKindCut + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Merged schema. // Ref: #/components/schemas/AssessmentCorrectiveAttempt type AssessmentCorrectiveAttempt struct { @@ -2484,6 +2674,310 @@ func (s *AssessmentFinalization) SetExpectedVersion(val AssessmentAttemptVersion s.ExpectedVersion = val } +// A finalize state conflict. `pending_item_ids` is present only when the attempt still has required +// questions without answers; it is omitted for other state conflicts and idempotency conflicts. +// Ref: #/components/schemas/AssessmentFinalizeConflictProblem +type AssessmentFinalizeConflictProblem struct { + Type string `json:"type"` + Title string `json:"title"` + Status int32 `json:"status"` + Code AssessmentFinalizeConflictProblemCode `json:"code"` + Detail OptString `json:"detail"` + Instance OptString `json:"instance"` + TraceID OptString `json:"trace_id"` + Errors []ProblemFieldError `json:"errors"` + // Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when + // the conflict is unrelated to unanswered items. + PendingItemIds []uuid.UUID `json:"pending_item_ids"` +} + +// GetType returns the value of Type. +func (s *AssessmentFinalizeConflictProblem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *AssessmentFinalizeConflictProblem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *AssessmentFinalizeConflictProblem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *AssessmentFinalizeConflictProblem) GetCode() AssessmentFinalizeConflictProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *AssessmentFinalizeConflictProblem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *AssessmentFinalizeConflictProblem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *AssessmentFinalizeConflictProblem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *AssessmentFinalizeConflictProblem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// GetPendingItemIds returns the value of PendingItemIds. +func (s *AssessmentFinalizeConflictProblem) GetPendingItemIds() []uuid.UUID { + return s.PendingItemIds +} + +// SetType sets the value of Type. +func (s *AssessmentFinalizeConflictProblem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *AssessmentFinalizeConflictProblem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *AssessmentFinalizeConflictProblem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *AssessmentFinalizeConflictProblem) SetCode(val AssessmentFinalizeConflictProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *AssessmentFinalizeConflictProblem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *AssessmentFinalizeConflictProblem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *AssessmentFinalizeConflictProblem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *AssessmentFinalizeConflictProblem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// SetPendingItemIds sets the value of PendingItemIds. +func (s *AssessmentFinalizeConflictProblem) SetPendingItemIds(val []uuid.UUID) { + s.PendingItemIds = val +} + +func (*AssessmentFinalizeConflictProblem) finalizeMyAssessmentAttemptRes() {} + +type AssessmentFinalizeConflictProblemCode string + +const ( + AssessmentFinalizeConflictProblemCodeStateConflict AssessmentFinalizeConflictProblemCode = "state_conflict" + AssessmentFinalizeConflictProblemCodeIdempotencyInProgress AssessmentFinalizeConflictProblemCode = "idempotency_in_progress" +) + +// AllValues returns all AssessmentFinalizeConflictProblemCode values. +func (AssessmentFinalizeConflictProblemCode) AllValues() []AssessmentFinalizeConflictProblemCode { + return []AssessmentFinalizeConflictProblemCode{ + AssessmentFinalizeConflictProblemCodeStateConflict, + AssessmentFinalizeConflictProblemCodeIdempotencyInProgress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentFinalizeConflictProblemCode) MarshalText() ([]byte, error) { + switch s { + case AssessmentFinalizeConflictProblemCodeStateConflict: + return []byte(s), nil + case AssessmentFinalizeConflictProblemCodeIdempotencyInProgress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentFinalizeConflictProblemCode) UnmarshalText(data []byte) error { + switch AssessmentFinalizeConflictProblemCode(data) { + case AssessmentFinalizeConflictProblemCodeStateConflict: + *s = AssessmentFinalizeConflictProblemCodeStateConflict + return nil + case AssessmentFinalizeConflictProblemCodeIdempotencyInProgress: + *s = AssessmentFinalizeConflictProblemCodeIdempotencyInProgress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/AssessmentFocusLossSignal +type AssessmentFocusLossSignal struct { + Kind AssessmentFocusLossSignalKind `json:"kind"` + ItemInstanceID AssessmentItemId `json:"item_instance_id"` + OccurredAt Timestamp `json:"occurred_at"` + // Client-measured duration away from the assessment tab or window, in milliseconds. + DurationMs int32 `json:"duration_ms"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentFocusLossSignal) GetKind() AssessmentFocusLossSignalKind { + return s.Kind +} + +// GetItemInstanceID returns the value of ItemInstanceID. +func (s *AssessmentFocusLossSignal) GetItemInstanceID() AssessmentItemId { + return s.ItemInstanceID +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *AssessmentFocusLossSignal) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// GetDurationMs returns the value of DurationMs. +func (s *AssessmentFocusLossSignal) GetDurationMs() int32 { + return s.DurationMs +} + +// SetKind sets the value of Kind. +func (s *AssessmentFocusLossSignal) SetKind(val AssessmentFocusLossSignalKind) { + s.Kind = val +} + +// SetItemInstanceID sets the value of ItemInstanceID. +func (s *AssessmentFocusLossSignal) SetItemInstanceID(val AssessmentItemId) { + s.ItemInstanceID = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *AssessmentFocusLossSignal) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +// SetDurationMs sets the value of DurationMs. +func (s *AssessmentFocusLossSignal) SetDurationMs(val int32) { + s.DurationMs = val +} + +type AssessmentFocusLossSignalKind string + +const ( + AssessmentFocusLossSignalKindFocusLoss AssessmentFocusLossSignalKind = "focus_loss" +) + +// AllValues returns all AssessmentFocusLossSignalKind values. +func (AssessmentFocusLossSignalKind) AllValues() []AssessmentFocusLossSignalKind { + return []AssessmentFocusLossSignalKind{ + AssessmentFocusLossSignalKindFocusLoss, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentFocusLossSignalKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentFocusLossSignalKindFocusLoss: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentFocusLossSignalKind) UnmarshalText(data []byte) error { + switch AssessmentFocusLossSignalKind(data) { + case AssessmentFocusLossSignalKindFocusLoss: + *s = AssessmentFocusLossSignalKindFocusLoss + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/AssessmentFullscreenExitSignal +type AssessmentFullscreenExitSignal struct { + Kind AssessmentFullscreenExitSignalKind `json:"kind"` + ItemInstanceID AssessmentItemId `json:"item_instance_id"` + OccurredAt Timestamp `json:"occurred_at"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentFullscreenExitSignal) GetKind() AssessmentFullscreenExitSignalKind { + return s.Kind +} + +// GetItemInstanceID returns the value of ItemInstanceID. +func (s *AssessmentFullscreenExitSignal) GetItemInstanceID() AssessmentItemId { + return s.ItemInstanceID +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *AssessmentFullscreenExitSignal) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// SetKind sets the value of Kind. +func (s *AssessmentFullscreenExitSignal) SetKind(val AssessmentFullscreenExitSignalKind) { + s.Kind = val +} + +// SetItemInstanceID sets the value of ItemInstanceID. +func (s *AssessmentFullscreenExitSignal) SetItemInstanceID(val AssessmentItemId) { + s.ItemInstanceID = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *AssessmentFullscreenExitSignal) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +type AssessmentFullscreenExitSignalKind string + +const ( + AssessmentFullscreenExitSignalKindFullscreenExit AssessmentFullscreenExitSignalKind = "fullscreen_exit" +) + +// AllValues returns all AssessmentFullscreenExitSignalKind values. +func (AssessmentFullscreenExitSignalKind) AllValues() []AssessmentFullscreenExitSignalKind { + return []AssessmentFullscreenExitSignalKind{ + AssessmentFullscreenExitSignalKindFullscreenExit, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentFullscreenExitSignalKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentFullscreenExitSignalKindFullscreenExit: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentFullscreenExitSignalKind) UnmarshalText(data []byte) error { + switch AssessmentFullscreenExitSignalKind(data) { + case AssessmentFullscreenExitSignalKindFullscreenExit: + *s = AssessmentFullscreenExitSignalKindFullscreenExit + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Domain of the specialization where the evidence was weak. // Ref: #/components/schemas/AssessmentGap type AssessmentGap struct { @@ -4181,6 +4675,261 @@ func (s *AssessmentSessions) SetIdleTimeoutSeconds(val int32) { s.IdleTimeoutSeconds = val } +// A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding +// and the batch contains at most 50 events. +// Ref: #/components/schemas/AssessmentSignalBatch +type AssessmentSignalBatch struct { + Events []AssessmentSignalEvent `json:"events"` +} + +// GetEvents returns the value of Events. +func (s *AssessmentSignalBatch) GetEvents() []AssessmentSignalEvent { + return s.Events +} + +// SetEvents sets the value of Events. +func (s *AssessmentSignalBatch) SetEvents(val []AssessmentSignalEvent) { + s.Events = val +} + +// One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input +// and is used only as event metadata; server receipt time is authoritative for limits and retention. +// Ref: #/components/schemas/AssessmentSignalEvent +// AssessmentSignalEvent represents sum type. +type AssessmentSignalEvent struct { + // Type selects the active sum variant, switch on this field. + Type AssessmentSignalEventType + AssessmentFocusLossSignal AssessmentFocusLossSignal + AssessmentClipboardSignal AssessmentClipboardSignal + AssessmentFullscreenExitSignal AssessmentFullscreenExitSignal +} + +// AssessmentSignalEventType is oneOf type of AssessmentSignalEvent. +type AssessmentSignalEventType string + +// Possible values for AssessmentSignalEventType. +const ( + AssessmentFocusLossSignalAssessmentSignalEvent AssessmentSignalEventType = "focus_loss" + AssessmentSignalEventCopyAssessmentSignalEvent AssessmentSignalEventType = "copy" + AssessmentSignalEventCutAssessmentSignalEvent AssessmentSignalEventType = "cut" + AssessmentSignalEventPasteAssessmentSignalEvent AssessmentSignalEventType = "paste" + AssessmentFullscreenExitSignalAssessmentSignalEvent AssessmentSignalEventType = "fullscreen_exit" +) + +// IsAssessmentFocusLossSignal reports whether AssessmentSignalEvent is AssessmentFocusLossSignal. +func (s AssessmentSignalEvent) IsAssessmentFocusLossSignal() bool { + return s.Type == AssessmentFocusLossSignalAssessmentSignalEvent +} + +// IsAssessmentClipboardSignal reports whether AssessmentSignalEvent is AssessmentClipboardSignal. +func (s AssessmentSignalEvent) IsAssessmentClipboardSignal() bool { + switch s.Type { + case AssessmentSignalEventCopyAssessmentSignalEvent, AssessmentSignalEventCutAssessmentSignalEvent, AssessmentSignalEventPasteAssessmentSignalEvent: + return true + default: + return false + } +} + +// IsAssessmentFullscreenExitSignal reports whether AssessmentSignalEvent is AssessmentFullscreenExitSignal. +func (s AssessmentSignalEvent) IsAssessmentFullscreenExitSignal() bool { + return s.Type == AssessmentFullscreenExitSignalAssessmentSignalEvent +} + +// SetAssessmentFocusLossSignal sets AssessmentSignalEvent to AssessmentFocusLossSignal. +func (s *AssessmentSignalEvent) SetAssessmentFocusLossSignal(v AssessmentFocusLossSignal) { + s.Type = AssessmentFocusLossSignalAssessmentSignalEvent + s.AssessmentFocusLossSignal = v +} + +// GetAssessmentFocusLossSignal returns AssessmentFocusLossSignal and true boolean if AssessmentSignalEvent is AssessmentFocusLossSignal. +func (s AssessmentSignalEvent) GetAssessmentFocusLossSignal() (v AssessmentFocusLossSignal, ok bool) { + if !s.IsAssessmentFocusLossSignal() { + return v, false + } + return s.AssessmentFocusLossSignal, true +} + +// NewAssessmentFocusLossSignalAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentFocusLossSignal. +func NewAssessmentFocusLossSignalAssessmentSignalEvent(v AssessmentFocusLossSignal) AssessmentSignalEvent { + var s AssessmentSignalEvent + s.SetAssessmentFocusLossSignal(v) + return s +} + +// SetAssessmentClipboardSignal sets AssessmentSignalEvent to AssessmentClipboardSignal. +// panics if `t` is not associated with AssessmentClipboardSignal +func (s *AssessmentSignalEvent) SetAssessmentClipboardSignal(t AssessmentSignalEventType, v AssessmentClipboardSignal) { + s.Type = t + s.AssessmentClipboardSignal = v + if !s.IsAssessmentClipboardSignal() { + panic(fmt.Errorf("invariant: %v is not AssessmentClipboardSignal", t)) + } +} + +// GetAssessmentClipboardSignal returns AssessmentClipboardSignal and true boolean if AssessmentSignalEvent is AssessmentClipboardSignal. +func (s AssessmentSignalEvent) GetAssessmentClipboardSignal() (v AssessmentClipboardSignal, ok bool) { + if !s.IsAssessmentClipboardSignal() { + return v, false + } + return s.AssessmentClipboardSignal, true +} + +// NewAssessmentSignalEventCopyAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentClipboardSignal. +func NewAssessmentSignalEventCopyAssessmentSignalEvent(v AssessmentClipboardSignal) AssessmentSignalEvent { + var s AssessmentSignalEvent + s.SetAssessmentClipboardSignal(AssessmentSignalEventCopyAssessmentSignalEvent, v) + return s +} + +// NewAssessmentSignalEventCutAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentClipboardSignal. +func NewAssessmentSignalEventCutAssessmentSignalEvent(v AssessmentClipboardSignal) AssessmentSignalEvent { + var s AssessmentSignalEvent + s.SetAssessmentClipboardSignal(AssessmentSignalEventCutAssessmentSignalEvent, v) + return s +} + +// NewAssessmentSignalEventPasteAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentClipboardSignal. +func NewAssessmentSignalEventPasteAssessmentSignalEvent(v AssessmentClipboardSignal) AssessmentSignalEvent { + var s AssessmentSignalEvent + s.SetAssessmentClipboardSignal(AssessmentSignalEventPasteAssessmentSignalEvent, v) + return s +} + +// SetAssessmentFullscreenExitSignal sets AssessmentSignalEvent to AssessmentFullscreenExitSignal. +func (s *AssessmentSignalEvent) SetAssessmentFullscreenExitSignal(v AssessmentFullscreenExitSignal) { + s.Type = AssessmentFullscreenExitSignalAssessmentSignalEvent + s.AssessmentFullscreenExitSignal = v +} + +// GetAssessmentFullscreenExitSignal returns AssessmentFullscreenExitSignal and true boolean if AssessmentSignalEvent is AssessmentFullscreenExitSignal. +func (s AssessmentSignalEvent) GetAssessmentFullscreenExitSignal() (v AssessmentFullscreenExitSignal, ok bool) { + if !s.IsAssessmentFullscreenExitSignal() { + return v, false + } + return s.AssessmentFullscreenExitSignal, true +} + +// NewAssessmentFullscreenExitSignalAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentFullscreenExitSignal. +func NewAssessmentFullscreenExitSignalAssessmentSignalEvent(v AssessmentFullscreenExitSignal) AssessmentSignalEvent { + var s AssessmentSignalEvent + s.SetAssessmentFullscreenExitSignal(v) + return s +} + +// Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, +// or result band. +// Ref: #/components/schemas/AssessmentSignalReceipt +type AssessmentSignalReceipt struct { + // `saturated` means no event from this batch was stored because the attempt's bounded evidence storage + // is full. + Status AssessmentSignalReceiptStatus `json:"status"` + // Number of events stored from this batch; zero when saturated. + AcceptedEvents int32 `json:"accepted_events"` + ReceivedAt Timestamp `json:"received_at"` +} + +// GetStatus returns the value of Status. +func (s *AssessmentSignalReceipt) GetStatus() AssessmentSignalReceiptStatus { + return s.Status +} + +// GetAcceptedEvents returns the value of AcceptedEvents. +func (s *AssessmentSignalReceipt) GetAcceptedEvents() int32 { + return s.AcceptedEvents +} + +// GetReceivedAt returns the value of ReceivedAt. +func (s *AssessmentSignalReceipt) GetReceivedAt() Timestamp { + return s.ReceivedAt +} + +// SetStatus sets the value of Status. +func (s *AssessmentSignalReceipt) SetStatus(val AssessmentSignalReceiptStatus) { + s.Status = val +} + +// SetAcceptedEvents sets the value of AcceptedEvents. +func (s *AssessmentSignalReceipt) SetAcceptedEvents(val int32) { + s.AcceptedEvents = val +} + +// SetReceivedAt sets the value of ReceivedAt. +func (s *AssessmentSignalReceipt) SetReceivedAt(val Timestamp) { + s.ReceivedAt = val +} + +// AssessmentSignalReceiptHeaders wraps AssessmentSignalReceipt with response headers. +type AssessmentSignalReceiptHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentSignalReceipt +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentSignalReceiptHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentSignalReceiptHeaders) GetResponse() AssessmentSignalReceipt { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentSignalReceiptHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentSignalReceiptHeaders) SetResponse(val AssessmentSignalReceipt) { + s.Response = val +} + +func (*AssessmentSignalReceiptHeaders) recordMyAssessmentAttemptSignalsRes() {} + +// `saturated` means no event from this batch was stored because the attempt's bounded evidence storage +// is full. +type AssessmentSignalReceiptStatus string + +const ( + AssessmentSignalReceiptStatusAccepted AssessmentSignalReceiptStatus = "accepted" + AssessmentSignalReceiptStatusSaturated AssessmentSignalReceiptStatus = "saturated" +) + +// AllValues returns all AssessmentSignalReceiptStatus values. +func (AssessmentSignalReceiptStatus) AllValues() []AssessmentSignalReceiptStatus { + return []AssessmentSignalReceiptStatus{ + AssessmentSignalReceiptStatusAccepted, + AssessmentSignalReceiptStatusSaturated, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentSignalReceiptStatus) MarshalText() ([]byte, error) { + switch s { + case AssessmentSignalReceiptStatusAccepted: + return []byte(s), nil + case AssessmentSignalReceiptStatusSaturated: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentSignalReceiptStatus) UnmarshalText(data []byte) error { + switch AssessmentSignalReceiptStatus(data) { + case AssessmentSignalReceiptStatusAccepted: + *s = AssessmentSignalReceiptStatusAccepted + return nil + case AssessmentSignalReceiptStatusSaturated: + *s = AssessmentSignalReceiptStatusSaturated + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Assessment state of one questionnaire specialization. Specializations are assessed independently, // with independent retry intervals. // Ref: #/components/schemas/AssessmentSpecializationAvailability @@ -4552,6 +5301,78 @@ func (s *CandidateExperience) SetAcademicMonths(val int32) { s.AcademicMonths = val } +// Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they +// are returned. +// Ref: #/components/schemas/CandidateExperienceBand +type CandidateExperienceBand string + +const ( + CandidateExperienceBand01 CandidateExperienceBand = "0_1" + CandidateExperienceBand13 CandidateExperienceBand = "1_3" + CandidateExperienceBand36 CandidateExperienceBand = "3_6" + CandidateExperienceBand6Plus CandidateExperienceBand = "6_plus" + CandidateExperienceBand03 CandidateExperienceBand = "0_3" + CandidateExperienceBand3Plus CandidateExperienceBand = "3_plus" +) + +// AllValues returns all CandidateExperienceBand values. +func (CandidateExperienceBand) AllValues() []CandidateExperienceBand { + return []CandidateExperienceBand{ + CandidateExperienceBand01, + CandidateExperienceBand13, + CandidateExperienceBand36, + CandidateExperienceBand6Plus, + CandidateExperienceBand03, + CandidateExperienceBand3Plus, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CandidateExperienceBand) MarshalText() ([]byte, error) { + switch s { + case CandidateExperienceBand01: + return []byte(s), nil + case CandidateExperienceBand13: + return []byte(s), nil + case CandidateExperienceBand36: + return []byte(s), nil + case CandidateExperienceBand6Plus: + return []byte(s), nil + case CandidateExperienceBand03: + return []byte(s), nil + case CandidateExperienceBand3Plus: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CandidateExperienceBand) UnmarshalText(data []byte) error { + switch CandidateExperienceBand(data) { + case CandidateExperienceBand01: + *s = CandidateExperienceBand01 + return nil + case CandidateExperienceBand13: + *s = CandidateExperienceBand13 + return nil + case CandidateExperienceBand36: + *s = CandidateExperienceBand36 + return nil + case CandidateExperienceBand6Plus: + *s = CandidateExperienceBand6Plus + return nil + case CandidateExperienceBand03: + *s = CandidateExperienceBand03 + return nil + case CandidateExperienceBand3Plus: + *s = CandidateExperienceBand3Plus + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + type CandidateHandle string // Invitation as the addressed candidate reads it: the organization, the current terms with their @@ -5500,11 +6321,104 @@ func (s *CandidateQuestionnaireUpdate) SetWorkContext(val WorkContext) { s.WorkContext = val } -// One access of an organization to the card or the contacts of the current candidate. `organization` -// is null for a view by an organization that has no invitation relation with the candidate, so the -// history shows that the card was viewed without naming a company that the candidate cannot otherwise -// see; whether the candidate should learn the name is an open product question. The record carries no -// query, ranking, or search filter of the organization. +// A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the +// anonymous card. +// Ref: #/components/schemas/CandidateSalaryCompatibility +type CandidateSalaryCompatibility string + +const ( + CandidateSalaryCompatibilityCompatible CandidateSalaryCompatibility = "compatible" + CandidateSalaryCompatibilityNotCompatible CandidateSalaryCompatibility = "not_compatible" +) + +// AllValues returns all CandidateSalaryCompatibility values. +func (CandidateSalaryCompatibility) AllValues() []CandidateSalaryCompatibility { + return []CandidateSalaryCompatibility{ + CandidateSalaryCompatibilityCompatible, + CandidateSalaryCompatibilityNotCompatible, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CandidateSalaryCompatibility) MarshalText() ([]byte, error) { + switch s { + case CandidateSalaryCompatibilityCompatible: + return []byte(s), nil + case CandidateSalaryCompatibilityNotCompatible: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CandidateSalaryCompatibility) UnmarshalText(data []byte) error { + switch CandidateSalaryCompatibility(data) { + case CandidateSalaryCompatibilityCompatible: + *s = CandidateSalaryCompatibilityCompatible + return nil + case CandidateSalaryCompatibilityNotCompatible: + *s = CandidateSalaryCompatibilityNotCompatible + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ref: #/components/schemas/CandidateWorkFormat +type CandidateWorkFormat string + +const ( + CandidateWorkFormatRemote CandidateWorkFormat = "remote" + CandidateWorkFormatOffice CandidateWorkFormat = "office" + CandidateWorkFormatHybrid CandidateWorkFormat = "hybrid" +) + +// AllValues returns all CandidateWorkFormat values. +func (CandidateWorkFormat) AllValues() []CandidateWorkFormat { + return []CandidateWorkFormat{ + CandidateWorkFormatRemote, + CandidateWorkFormatOffice, + CandidateWorkFormatHybrid, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CandidateWorkFormat) MarshalText() ([]byte, error) { + switch s { + case CandidateWorkFormatRemote: + return []byte(s), nil + case CandidateWorkFormatOffice: + return []byte(s), nil + case CandidateWorkFormatHybrid: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CandidateWorkFormat) UnmarshalText(data []byte) error { + switch CandidateWorkFormat(data) { + case CandidateWorkFormatRemote: + *s = CandidateWorkFormatRemote + return nil + case CandidateWorkFormatOffice: + *s = CandidateWorkFormatOffice + return nil + case CandidateWorkFormatHybrid: + *s = CandidateWorkFormatHybrid + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One access of an organization to the card or the contacts of the current candidate. A retained +// access permits the candidate to see the organization's identifier and current name and to hide their +// profile from it. `organization` is null when the organization cannot be presented. Earlier permitted +// accesses remain after hiding. The record carries no employee identity, query, ranking, or search +// filter of the organization. // Ref: #/components/schemas/CardAccess type CardAccess struct { // Identifier of the access record. @@ -5556,7 +6470,7 @@ func (s *CardAccess) SetOrganization(val NilPrivacyOrganization) { // How an organization reached the candidate. // -// - card_viewed: an organization read the anonymous card in a search result. +// - card_viewed: an organization read the permitted anonymous card. // - contact_read: an organization read the contacts through the contact grant of an accepted // invitation. // @@ -5663,6 +6577,8 @@ func (*CardAccessListHeaders) listMyCardAccessHistoryRes() {} type CardCategory struct { Specialization SpecializationCode `json:"specialization"` Grade GradeCode `json:"grade"` + // Coarse strength of the authoritative confirmation. + Strength CardCategoryStrength `json:"strength"` } // GetSpecialization returns the value of Specialization. @@ -5675,6 +6591,11 @@ func (s *CardCategory) GetGrade() GradeCode { return s.Grade } +// GetStrength returns the value of Strength. +func (s *CardCategory) GetStrength() CardCategoryStrength { + return s.Strength +} + // SetSpecialization sets the value of Specialization. func (s *CardCategory) SetSpecialization(val SpecializationCode) { s.Specialization = val @@ -5685,19 +6606,68 @@ func (s *CardCategory) SetGrade(val GradeCode) { s.Grade = val } +// SetStrength sets the value of Strength. +func (s *CardCategory) SetStrength(val CardCategoryStrength) { + s.Strength = val +} + +// Coarse strength of the authoritative confirmation. +type CardCategoryStrength string + +const ( + CardCategoryStrengthStandard CardCategoryStrength = "standard" + CardCategoryStrengthStrong CardCategoryStrength = "strong" +) + +// AllValues returns all CardCategoryStrength values. +func (CardCategoryStrength) AllValues() []CardCategoryStrength { + return []CardCategoryStrength{ + CardCategoryStrengthStandard, + CardCategoryStrengthStrong, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CardCategoryStrength) MarshalText() ([]byte, error) { + switch s { + case CardCategoryStrengthStandard: + return []byte(s), nil + case CardCategoryStrengthStrong: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CardCategoryStrength) UnmarshalText(data []byte) error { + switch CardCategoryStrength(data) { + case CardCategoryStrengthStandard: + *s = CardCategoryStrengthStandard + return nil + case CardCategoryStrengthStrong: + *s = CardCategoryStrengthStrong + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // A group of values of the anonymous candidate card that the candidate chooses to publish. The set is // closed and has no value for the full name, a contact, or the lowest salary: the card never carries // them, so no choice and no later contract change in this list can publish them by accident. Contacts // leave only through the contact grant of an accepted invitation (C4), and the lowest salary never // leaves. // -// - categories: the categories confirmed by assessment results (specialization and confirmed grade). -// A self-assessed grade is not a category and is never published. -// - stack: the technology tags of the profile. -// - experience: the total months of work experience, without employers, periods, or descriptions. -// - soft_skills: the soft skills of the profile. -// - location: the city or region of the profile. -// - relocation: whether the candidate is ready to relocate. +// - categories: specialization and grade confirmed by an authoritative assessment result. +// - self_assessment: the candidate's declared specialization and grade, separate from confirmed +// categories. +// - stack: only recognized technology codes from the server's closed taxonomy. +// - experience: a coarse total-experience band, without employers, periods, or descriptions. +// - work_formats: explicitly selected work formats from the private questionnaire. +// - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. +// - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; +// they are not returned by the anonymous card. // // Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status // `extracted`) and an unknown value never do, whatever the field set says. @@ -5710,23 +6680,29 @@ func (s *CardCategory) SetGrade(val GradeCode) { type CardField string const ( - CardFieldCategories CardField = "categories" - CardFieldStack CardField = "stack" - CardFieldExperience CardField = "experience" - CardFieldSoftSkills CardField = "soft_skills" - CardFieldLocation CardField = "location" - CardFieldRelocation CardField = "relocation" + CardFieldCategories CardField = "categories" + CardFieldSalaryCompatibility CardField = "salary_compatibility" + CardFieldSelfAssessment CardField = "self_assessment" + CardFieldStack CardField = "stack" + CardFieldExperience CardField = "experience" + CardFieldSoftSkills CardField = "soft_skills" + CardFieldLocation CardField = "location" + CardFieldRelocation CardField = "relocation" + CardFieldWorkFormats CardField = "work_formats" ) // AllValues returns all CardField values. func (CardField) AllValues() []CardField { return []CardField{ CardFieldCategories, + CardFieldSalaryCompatibility, + CardFieldSelfAssessment, CardFieldStack, CardFieldExperience, CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation, + CardFieldWorkFormats, } } @@ -5735,6 +6711,10 @@ func (s CardField) MarshalText() ([]byte, error) { switch s { case CardFieldCategories: return []byte(s), nil + case CardFieldSalaryCompatibility: + return []byte(s), nil + case CardFieldSelfAssessment: + return []byte(s), nil case CardFieldStack: return []byte(s), nil case CardFieldExperience: @@ -5745,6 +6725,8 @@ func (s CardField) MarshalText() ([]byte, error) { return []byte(s), nil case CardFieldRelocation: return []byte(s), nil + case CardFieldWorkFormats: + return []byte(s), nil default: return nil, errors.Errorf("invalid value: %q", s) } @@ -5756,6 +6738,12 @@ func (s *CardField) UnmarshalText(data []byte) error { case CardFieldCategories: *s = CardFieldCategories return nil + case CardFieldSalaryCompatibility: + *s = CardFieldSalaryCompatibility + return nil + case CardFieldSelfAssessment: + *s = CardFieldSelfAssessment + return nil case CardFieldStack: *s = CardFieldStack return nil @@ -5771,6 +6759,9 @@ func (s *CardField) UnmarshalText(data []byte) error { case CardFieldRelocation: *s = CardFieldRelocation return nil + case CardFieldWorkFormats: + *s = CardFieldWorkFormats + return nil default: return errors.Errorf("invalid value: %q", data) } @@ -5778,10 +6769,11 @@ func (s *CardField) UnmarshalText(data []byte) error { type CardFieldSet []CardField -// What an organization that the candidate does not hide the profile from would read now, computed from -// the current profile, the current publication, and the consent ledger. It is a read for the -// candidate: it creates no view and no history record, and it never reaches an organization. `card` is -// null while the profile is closed. +// A private candidate preview computed from the current profile, publication, and consent ledger. Its +// pseudonym uses a separate preview context and is not an organization's alias. Organization-specific +// visibility filters and cohort checks can further generalize or suppress the organization-facing +// card. This read creates no view or history record and never reaches an organization. `card` is null +// while the profile is closed. // Ref: #/components/schemas/CardPreview type CardPreview struct { State PublicationState `json:"state"` @@ -5858,6 +6850,85 @@ func (s *CardPreviewHeaders) SetResponse(val CardPreview) { func (*CardPreviewHeaders) getMyCardPreviewRes() {} +// Candidate-declared specialization and optional grade. This is never an assessment result. +// Ref: #/components/schemas/CardSelfAssessment +type CardSelfAssessment struct { + Specialization SpecializationCode `json:"specialization"` + ConfirmationStatus CardSelfAssessmentConfirmationStatus `json:"confirmation_status"` + DeclaredGrade OptNilGradeCode `json:"declared_grade"` +} + +// GetSpecialization returns the value of Specialization. +func (s *CardSelfAssessment) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetConfirmationStatus returns the value of ConfirmationStatus. +func (s *CardSelfAssessment) GetConfirmationStatus() CardSelfAssessmentConfirmationStatus { + return s.ConfirmationStatus +} + +// GetDeclaredGrade returns the value of DeclaredGrade. +func (s *CardSelfAssessment) GetDeclaredGrade() OptNilGradeCode { + return s.DeclaredGrade +} + +// SetSpecialization sets the value of Specialization. +func (s *CardSelfAssessment) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetConfirmationStatus sets the value of ConfirmationStatus. +func (s *CardSelfAssessment) SetConfirmationStatus(val CardSelfAssessmentConfirmationStatus) { + s.ConfirmationStatus = val +} + +// SetDeclaredGrade sets the value of DeclaredGrade. +func (s *CardSelfAssessment) SetDeclaredGrade(val OptNilGradeCode) { + s.DeclaredGrade = val +} + +type CardSelfAssessmentConfirmationStatus string + +const ( + CardSelfAssessmentConfirmationStatusConfirmed CardSelfAssessmentConfirmationStatus = "confirmed" + CardSelfAssessmentConfirmationStatusUnconfirmed CardSelfAssessmentConfirmationStatus = "unconfirmed" +) + +// AllValues returns all CardSelfAssessmentConfirmationStatus values. +func (CardSelfAssessmentConfirmationStatus) AllValues() []CardSelfAssessmentConfirmationStatus { + return []CardSelfAssessmentConfirmationStatus{ + CardSelfAssessmentConfirmationStatusConfirmed, + CardSelfAssessmentConfirmationStatusUnconfirmed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CardSelfAssessmentConfirmationStatus) MarshalText() ([]byte, error) { + switch s { + case CardSelfAssessmentConfirmationStatusConfirmed: + return []byte(s), nil + case CardSelfAssessmentConfirmationStatusUnconfirmed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CardSelfAssessmentConfirmationStatus) UnmarshalText(data []byte) error { + switch CardSelfAssessmentConfirmationStatus(data) { + case CardSelfAssessmentConfirmationStatusConfirmed: + *s = CardSelfAssessmentConfirmationStatusConfirmed + return nil + case CardSelfAssessmentConfirmationStatusUnconfirmed: + *s = CardSelfAssessmentConfirmationStatusUnconfirmed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Professional direction with its specializations. Each specialization belongs to exactly one // direction. // Ref: #/components/schemas/CatalogDirection @@ -8147,10 +9218,6 @@ type FinalizeMyAssessmentAttemptBadRequest Problem func (*FinalizeMyAssessmentAttemptBadRequest) finalizeMyAssessmentAttemptRes() {} -type FinalizeMyAssessmentAttemptConflict Problem - -func (*FinalizeMyAssessmentAttemptConflict) finalizeMyAssessmentAttemptRes() {} - type FinalizeMyAssessmentAttemptForbidden Problem func (*FinalizeMyAssessmentAttemptForbidden) finalizeMyAssessmentAttemptRes() {} @@ -8457,6 +9524,22 @@ type GetOrganizationBadRequest Problem func (*GetOrganizationBadRequest) getOrganizationRes() {} +type GetOrganizationCandidateCardBadRequest Problem + +func (*GetOrganizationCandidateCardBadRequest) getOrganizationCandidateCardRes() {} + +type GetOrganizationCandidateCardForbidden Problem + +func (*GetOrganizationCandidateCardForbidden) getOrganizationCandidateCardRes() {} + +type GetOrganizationCandidateCardNotFound Problem + +func (*GetOrganizationCandidateCardNotFound) getOrganizationCandidateCardRes() {} + +type GetOrganizationCandidateCardUnauthorized Problem + +func (*GetOrganizationCandidateCardUnauthorized) getOrganizationCandidateCardRes() {} + type GetOrganizationForbidden Problem func (*GetOrganizationForbidden) getOrganizationRes() {} @@ -13326,6 +14409,96 @@ func (o NilCandidateExperience) Or(d CandidateExperience) CandidateExperience { return d } +// NewNilCandidateExperienceBand returns new NilCandidateExperienceBand with value set to v. +func NewNilCandidateExperienceBand(v CandidateExperienceBand) NilCandidateExperienceBand { + return NilCandidateExperienceBand{ + Value: v, + } +} + +// NilCandidateExperienceBand is nullable CandidateExperienceBand. +type NilCandidateExperienceBand struct { + Value CandidateExperienceBand + Null bool +} + +// SetTo sets value to v. +func (o *NilCandidateExperienceBand) SetTo(v CandidateExperienceBand) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilCandidateExperienceBand) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilCandidateExperienceBand) SetToNull() { + o.Null = true + var v CandidateExperienceBand + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilCandidateExperienceBand) Get() (v CandidateExperienceBand, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilCandidateExperienceBand) Or(d CandidateExperienceBand) CandidateExperienceBand { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilCandidateSalaryCompatibility returns new NilCandidateSalaryCompatibility with value set to v. +func NewNilCandidateSalaryCompatibility(v CandidateSalaryCompatibility) NilCandidateSalaryCompatibility { + return NilCandidateSalaryCompatibility{ + Value: v, + } +} + +// NilCandidateSalaryCompatibility is nullable CandidateSalaryCompatibility. +type NilCandidateSalaryCompatibility struct { + Value CandidateSalaryCompatibility + Null bool +} + +// SetTo sets value to v. +func (o *NilCandidateSalaryCompatibility) SetTo(v CandidateSalaryCompatibility) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilCandidateSalaryCompatibility) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilCandidateSalaryCompatibility) SetToNull() { + o.Null = true + var v CandidateSalaryCompatibility + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilCandidateSalaryCompatibility) Get() (v CandidateSalaryCompatibility, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilCandidateSalaryCompatibility) Or(d CandidateSalaryCompatibility) CandidateSalaryCompatibility { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilConsentOrganization returns new NilConsentOrganization with value set to v. func NewNilConsentOrganization(v ConsentOrganization) NilConsentOrganization { return NilConsentOrganization{ @@ -13866,51 +15039,6 @@ func (o NilGradeCode) Or(d GradeCode) GradeCode { return d } -// NewNilInt returns new NilInt with value set to v. -func NewNilInt(v int) NilInt { - return NilInt{ - Value: v, - } -} - -// NilInt is nullable int. -type NilInt struct { - Value int - Null bool -} - -// SetTo sets value to v. -func (o *NilInt) SetTo(v int) { - o.Null = false - o.Value = v -} - -// IsNull returns true if value is Null. -func (o NilInt) IsNull() bool { return o.Null } - -// SetToNull sets value to null. -func (o *NilInt) SetToNull() { - o.Null = true - var v int - o.Value = v -} - -// Get returns value and boolean that denotes whether value was set. -func (o NilInt) Get() (v int, ok bool) { - if o.Null { - return v, false - } - return o.Value, true -} - -// Or returns value if set, or given parameter if does not. -func (o NilInt) Or(d int) int { - if v, ok := o.Get(); ok { - return v - } - return d -} - // NewNilInt32 returns new NilInt32 with value set to v. func NewNilInt32(v int32) NilInt32 { return NilInt32{ @@ -16165,8 +17293,8 @@ func (o NilWorkContext) Or(d WorkContext) WorkContext { // numerically equal, so 254 and 254.0 are the same answer. // Ref: #/components/schemas/NumberAnswer type NumberAnswer struct { - Format NumberAnswerFormat `json:"format"` - Number float64 `json:"number"` + Format NumberAnswerFormat `json:"format"` + Number apitypes.AssessmentNumber `json:"number"` } // GetFormat returns the value of Format. @@ -16175,7 +17303,7 @@ func (s *NumberAnswer) GetFormat() NumberAnswerFormat { } // GetNumber returns the value of Number. -func (s *NumberAnswer) GetNumber() float64 { +func (s *NumberAnswer) GetNumber() apitypes.AssessmentNumber { return s.Number } @@ -16185,7 +17313,7 @@ func (s *NumberAnswer) SetFormat(val NumberAnswerFormat) { } // SetNumber sets the value of Number. -func (s *NumberAnswer) SetNumber(val float64) { +func (s *NumberAnswer) SetNumber(val apitypes.AssessmentNumber) { s.Number = val } @@ -16600,6 +17728,74 @@ func (o OptNeedTitle) Or(d NeedTitle) NeedTitle { return d } +// NewOptNilGradeCode returns new OptNilGradeCode with value set to v. +func NewOptNilGradeCode(v GradeCode) OptNilGradeCode { + return OptNilGradeCode{ + Value: v, + Set: true, + } +} + +// OptNilGradeCode is optional nullable GradeCode. +type OptNilGradeCode struct { + Value GradeCode + Set bool + Null bool +} + +// IsSet returns true if OptNilGradeCode was set. +func (o OptNilGradeCode) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptNilGradeCode) Reset() { + var v GradeCode + o.Value = v + o.Set = false + o.Null = false +} + +// SetTo sets value to v. +func (o *OptNilGradeCode) SetTo(v GradeCode) { + o.Set = true + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o OptNilGradeCode) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *OptNilGradeCode) SetToNull() { + o.Set = true + o.Null = true + var v GradeCode + o.Value = v +} + +// IsEmpty returns true if the field was omitted from the payload (not Set and not Null). +func (o OptNilGradeCode) IsEmpty() bool { + return !o.Set && !o.Null +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptNilGradeCode) Get() (v GradeCode, ok bool) { + if o.Null { + return v, false + } + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptNilGradeCode) Or(d GradeCode) GradeCode { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptNilInvitationDeclineComment returns new OptNilInvitationDeclineComment with value set to v. func NewOptNilInvitationDeclineComment(v InvitationDeclineComment) OptNilInvitationDeclineComment { return OptNilInvitationDeclineComment{ @@ -22455,6 +23651,34 @@ type RaiseOrganizationInvitationSalaryUnprocessableEntity Problem func (*RaiseOrganizationInvitationSalaryUnprocessableEntity) raiseOrganizationInvitationSalaryRes() {} +type RecordMyAssessmentAttemptSignalsBadRequest Problem + +func (*RecordMyAssessmentAttemptSignalsBadRequest) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsConflict Problem + +func (*RecordMyAssessmentAttemptSignalsConflict) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsForbidden Problem + +func (*RecordMyAssessmentAttemptSignalsForbidden) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsNotFound Problem + +func (*RecordMyAssessmentAttemptSignalsNotFound) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsRequestEntityTooLarge Problem + +func (*RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsUnauthorized Problem + +func (*RecordMyAssessmentAttemptSignalsUnauthorized) recordMyAssessmentAttemptSignalsRes() {} + +type RecordMyAssessmentAttemptSignalsUnprocessableEntity Problem + +func (*RecordMyAssessmentAttemptSignalsUnprocessableEntity) recordMyAssessmentAttemptSignalsRes() {} + type RegisterAccountBadRequest Problem func (*RegisterAccountBadRequest) registerAccountRes() {} @@ -23451,10 +24675,10 @@ type SupportCase struct { AssessmentTarget NilSupportCaseAssessmentTarget `json:"assessment_target"` // Ground of a complaint, or null for other types. ComplaintReason NilSupportCaseComplaintReason `json:"complaint_reason"` - // For a manual assessment, the version of the published rubric of the category that the server fixed - // on creation; the expert assesses with it, the same rubric as the automated assessment. Null for - // other types, and null for a manual assessment whose category has no published rubric yet: the case - // then waits in `waiting_expert` and the client says so instead of promising a date. + // For a manual assessment, the version of the grading policy pinned by the server at creation. The + // exact reviewed category opening and rubric manifest are retained privately so the expert can use the + // same rubric as automated assessment. Null for other types and for a manual assessment without one + // unique current reviewed category; the case still waits in `waiting_expert`. RubricVersion NilInt32 `json:"rubric_version"` ResponseTarget SupportResponseTarget `json:"response_target"` // Decision once the case is `resolved`, otherwise null. @@ -25562,9 +26786,11 @@ func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} func (*TooManyRequestsHeaders) createOrganizationRes() {} func (*TooManyRequestsHeaders) declineMyInvitationRes() {} +func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {} func (*TooManyRequestsHeaders) hideOrganizationRes() {} func (*TooManyRequestsHeaders) loginRes() {} func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} +func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {} func (*TooManyRequestsHeaders) registerAccountRes() {} func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} func (*TooManyRequestsHeaders) sendOrganizationInvitationRes() {} diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index d478c28..7cddb5f 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -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{}, diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index aae64c0..8dd9c11 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -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 diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 755abeb..6184021 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -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 diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index c0ebf16..097bf3e 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -161,6 +161,29 @@ func (s *AnonymousCardContent) Validate() error { } var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 47, + MinLengthSet: true, + MaxLength: 47, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^cv1_[A-Za-z0-9_-]{43}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pseudonym)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pseudonym", + Error: err, + }) + } if err := func() error { if s.Categories == nil { return nil // null @@ -204,7 +227,7 @@ func (s *AnonymousCardContent) Validate() error { if err := (validate.Array{ MinLength: 0, MinLengthSet: false, - MaxLength: 30, + MaxLength: 4, MaxLengthSet: true, }).ValidateLength(len(s.Stack)); err != nil { return errors.Wrap(err, "array") @@ -234,62 +257,22 @@ func (s *AnonymousCardContent) Validate() error { }) } if err := func() error { - if value, ok := s.ExperienceMonths.Get(); ok { - if err := func() error { - if err := (validate.Int{ - MinSet: true, - Min: 0, - MaxSet: true, - Max: 1200, - MinExclusive: false, - MaxExclusive: false, - MultipleOfSet: false, - MultipleOf: 0, - Pattern: nil, - }).Validate(int64(value)); err != nil { - return errors.Wrap(err, "int") - } - return nil - }(); err != nil { - return err - } - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "experience_months", - Error: err, - }) - } - if err := func() error { - if s.SoftSkills == nil { + if s.SelfAssessment == nil { return nil // null } if err := (validate.Array{ MinLength: 0, MinLengthSet: false, - MaxLength: 10, + MaxLength: 9, MaxLengthSet: true, - }).ValidateLength(len(s.SoftSkills)); err != nil { + }).ValidateLength(len(s.SelfAssessment)); err != nil { return errors.Wrap(err, "array") } var failures []validate.FieldError - for i, elem := range s.SoftSkills { + for i, elem := range s.SelfAssessment { if err := func() error { - if err := (validate.String{ - MinLength: 1, - MinLengthSet: true, - MaxLength: 50, - MaxLengthSet: true, - Email: false, - Hostname: false, - Regex: regexMap["^\\S(?:.*\\S)?$"], - MinNumeric: 0, - MinNumericSet: false, - MaxNumeric: 0, - MaxNumericSet: false, - }).Validate(string(elem)); err != nil { - return errors.Wrap(err, "string") + if err := elem.Validate(); err != nil { + return err } return nil }(); err != nil { @@ -305,27 +288,15 @@ func (s *AnonymousCardContent) Validate() error { return nil }(); err != nil { failures = append(failures, validate.FieldError{ - Name: "soft_skills", + Name: "self_assessment", Error: err, }) } if err := func() error { - if value, ok := s.Location.Get(); ok { + if value, ok := s.ExperienceBand.Get(); ok { if err := func() error { - if err := (validate.String{ - MinLength: 1, - MinLengthSet: true, - MaxLength: 100, - MaxLengthSet: true, - Email: false, - Hostname: false, - Regex: regexMap["^\\S(?:.*\\S)?$"], - MinNumeric: 0, - MinNumericSet: false, - MaxNumeric: 0, - MaxNumericSet: false, - }).Validate(string(value)); err != nil { - return errors.Wrap(err, "string") + if err := value.Validate(); err != nil { + return err } return nil }(); err != nil { @@ -335,7 +306,61 @@ func (s *AnonymousCardContent) Validate() error { return nil }(); err != nil { failures = append(failures, validate.FieldError{ - Name: "location", + Name: "experience_band", + Error: err, + }) + } + if err := func() error { + if s.WorkFormats == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 3, + MaxLengthSet: true, + }).ValidateLength(len(s.WorkFormats)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.WorkFormats { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "work_formats", + Error: err, + }) + } + if err := func() error { + if value, ok := s.SalaryCompatibility.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary_compatibility", Error: err, }) } @@ -345,6 +370,55 @@ func (s *AnonymousCardContent) Validate() error { return nil } +func (s *AnonymousCardContentHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AnonymousCardContentStackItem) Validate() error { + switch s { + case "go": + return nil + case "postgresql": + return nil + case "kafka": + return nil + case "docker": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s AssessmentAnswer) Validate() error { switch s.Type { case ChoiceAnswerAssessmentAnswer: @@ -643,6 +717,63 @@ func (s *AssessmentAvailabilityHeaders) Validate() error { return nil } +func (s *AssessmentClipboardSignal) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 2147483647, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.SizeBytes)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "size_bytes", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentClipboardSignalKind) Validate() error { + switch s { + case "copy": + return nil + case "paste": + return nil + case "cut": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentCorrectiveAttempt) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1960,6 +2091,319 @@ func (s *AssessmentFinalization) Validate() error { return nil } +func (s *AssessmentFinalizeConflictProblem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "errors", + Error: err, + }) + } + if err := func() error { + if s.PendingItemIds == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 220, + MaxLengthSet: true, + }).ValidateLength(len(s.PendingItemIds)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.PendingItemIds); err != nil { + return errors.Wrap(err, "array") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pending_item_ids", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentFinalizeConflictProblemCode) Validate() error { + switch s { + case "state_conflict": + return nil + case "idempotency_in_progress": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentFocusLossSignal) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 259200000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.DurationMs)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "duration_ms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentFocusLossSignalKind) Validate() error { + switch s { + case "focus_loss": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentFullscreenExitSignal) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentFullscreenExitSignalKind) Validate() error { + switch s { + case "fullscreen_exit": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentGap) Validate() error { if s == nil { return validate.ErrNilPointer @@ -3417,6 +3861,165 @@ func (s *AssessmentSessions) Validate() error { return nil } +func (s *AssessmentSignalBatch) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Events == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Events)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Events { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "events", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentSignalEvent) Validate() error { + switch s.Type { + case AssessmentFocusLossSignalAssessmentSignalEvent: + if err := s.AssessmentFocusLossSignal.Validate(); err != nil { + return err + } + return nil + case AssessmentSignalEventCopyAssessmentSignalEvent, AssessmentSignalEventCutAssessmentSignalEvent, AssessmentSignalEventPasteAssessmentSignalEvent: + if err := s.AssessmentClipboardSignal.Validate(); err != nil { + return err + } + return nil + case AssessmentFullscreenExitSignalAssessmentSignalEvent: + if err := s.AssessmentFullscreenExitSignal.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + +func (s *AssessmentSignalReceipt) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.AcceptedEvents)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted_events", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentSignalReceiptHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentSignalReceiptStatus) Validate() error { + switch s { + case "accepted": + return nil + case "saturated": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentSpecializationAvailability) Validate() error { if s == nil { return validate.ErrNilPointer @@ -3861,16 +4464,35 @@ func (s *CandidateExperience) Validate() error { return nil } +func (s CandidateExperienceBand) Validate() error { + switch s { + case "0_1": + return nil + case "1_3": + return nil + case "3_6": + return nil + case "6_plus": + return nil + case "0_3": + return nil + case "3_plus": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s CandidateHandle) Validate() error { alias := (string)(s) if err := (validate.String{ - MinLength: 1, + MinLength: 47, MinLengthSet: true, - MaxLength: 128, + MaxLength: 47, MaxLengthSet: true, Email: false, Hostname: false, - Regex: regexMap["^[A-Za-z0-9_-]+$"], + Regex: regexMap["^cv1_[A-Za-z0-9_-]{43}$"], MinNumeric: 0, MinNumericSet: false, MaxNumeric: 0, @@ -5136,6 +5758,30 @@ func (s *CandidateQuestionnaireUpdate) Validate() error { return nil } +func (s CandidateSalaryCompatibility) Validate() error { + switch s { + case "compatible": + return nil + case "not_compatible": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s CandidateWorkFormat) Validate() error { + switch s { + case "remote": + return nil + case "office": + return nil + case "hybrid": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *CardAccess) Validate() error { if s == nil { return validate.ErrNilPointer @@ -5309,16 +5955,42 @@ func (s *CardCategory) Validate() error { Error: err, }) } + if err := func() error { + if err := s.Strength.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "strength", + Error: err, + }) + } if len(failures) > 0 { return &validate.Error{Fields: failures} } return nil } +func (s CardCategoryStrength) Validate() error { + switch s { + case "standard": + return nil + case "strong": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s CardField) Validate() error { switch s { case "categories": return nil + case "salary_compatibility": + return nil + case "self_assessment": + return nil case "stack": return nil case "experience": @@ -5329,6 +6001,8 @@ func (s CardField) Validate() error { return nil case "relocation": return nil + case "work_formats": + return nil default: return errors.Errorf("invalid value: %v", s) } @@ -5342,7 +6016,7 @@ func (s CardFieldSet) Validate() error { if err := (validate.Array{ MinLength: 0, MinLengthSet: true, - MaxLength: 6, + MaxLength: 9, MaxLengthSet: true, }).ValidateLength(len(alias)); err != nil { return errors.Wrap(err, "array") @@ -5456,6 +6130,69 @@ func (s *CardPreviewHeaders) Validate() error { return nil } +func (s *CardSelfAssessment) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.ConfirmationStatus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "confirmation_status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.DeclaredGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "declared_grade", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s CardSelfAssessmentConfirmationStatus) Validate() error { + switch s { + case "confirmed": + return nil + case "unconfirmed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *CatalogDirection) Validate() error { if s == nil { return validate.ErrNilPointer @@ -7682,14 +8419,6 @@ func (s *FinalizeMyAssessmentAttemptBadRequest) Validate() error { return nil } -func (s *FinalizeMyAssessmentAttemptConflict) Validate() error { - alias := (*Problem)(s) - if err := alias.Validate(); err != nil { - return err - } - return nil -} - func (s *FinalizeMyAssessmentAttemptForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -8180,6 +8909,38 @@ func (s *GetOrganizationBadRequest) Validate() error { return nil } +func (s *GetOrganizationCandidateCardBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationCandidateCardForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationCandidateCardNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationCandidateCardUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetOrganizationForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -12793,17 +13554,6 @@ func (s *NumberAnswer) Validate() error { Error: err, }) } - if err := func() error { - if err := (validate.Float{}).Validate(float64(s.Number)); err != nil { - return errors.Wrap(err, "float") - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "number", - Error: err, - }) - } if len(failures) > 0 { return &validate.Error{Fields: failures} } @@ -17875,6 +18625,62 @@ func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) Validate() error return nil } +func (s *RecordMyAssessmentAttemptSignalsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RecordMyAssessmentAttemptSignalsUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *RegisterAccountBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { diff --git a/backend/internal/adapter/primary/http/apitypes/assessment_number.go b/backend/internal/adapter/primary/http/apitypes/assessment_number.go new file mode 100644 index 0000000..03904be --- /dev/null +++ b/backend/internal/adapter/primary/http/apitypes/assessment_number.go @@ -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) +} diff --git a/backend/internal/adapter/primary/http/apitypes/assessment_number_test.go b/backend/internal/adapter/primary/http/apitypes/assessment_number_test.go new file mode 100644 index 0000000..1942bdd --- /dev/null +++ b/backend/internal/adapter/primary/http/apitypes/assessment_number_test.go @@ -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) + } + } +} diff --git a/backend/internal/adapter/primary/http/assessment_signal_body.go b/backend/internal/adapter/primary/http/assessment_signal_body.go new file mode 100644 index 0000000..8c49f23 --- /dev/null +++ b/backend/internal/adapter/primary/http/assessment_signal_body.go @@ -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) + } +} diff --git a/backend/internal/adapter/primary/http/assessment_signal_body_test.go b/backend/internal/adapter/primary/http/assessment_signal_body_test.go new file mode 100644 index 0000000..de120ff --- /dev/null +++ b/backend/internal/adapter/primary/http/assessment_signal_body_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go index ca3c35d..e97a737 100644 --- a/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go +++ b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go @@ -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) } diff --git a/backend/internal/adapter/primary/http/company_context_test.go b/backend/internal/adapter/primary/http/company_context_test.go index 18cf57a..04948ba 100644 --- a/backend/internal/adapter/primary/http/company_context_test.go +++ b/backend/internal/adapter/primary/http/company_context_test.go @@ -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 { diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index 59fab39..448db65 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -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" diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index c61c5d0..1efe68c 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -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", }, { diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go index 4b6232f..ffabce7 100644 --- a/backend/internal/adapter/primary/http/v1/api.go +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -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 { diff --git a/backend/internal/adapter/primary/http/v1/assessment.go b/backend/internal/adapter/primary/http/v1/assessment.go new file mode 100644 index 0000000..6f141c6 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment.go @@ -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") + } +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_availability.go b/backend/internal/adapter/primary/http/v1/assessment_availability.go new file mode 100644 index 0000000..ca39050 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_availability.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_availability_test.go b/backend/internal/adapter/primary/http/v1/assessment_availability_test.go new file mode 100644 index 0000000..80226f9 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_availability_test.go @@ -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() } diff --git a/backend/internal/adapter/primary/http/v1/assessment_signal.go b/backend/internal/adapter/primary/http/v1/assessment_signal.go new file mode 100644 index 0000000..a3d7971 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_signal.go @@ -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 + } +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_signal_test.go b/backend/internal/adapter/primary/http/v1/assessment_signal_test.go new file mode 100644 index 0000000..03bd76b --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_signal_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_test.go b/backend/internal/adapter/primary/http/v1/assessment_test.go new file mode 100644 index 0000000..7bb70d7 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_test.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/need.go b/backend/internal/adapter/primary/http/v1/need.go new file mode 100644 index 0000000..09b1730 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/need.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/need_test.go b/backend/internal/adapter/primary/http/v1/need_test.go new file mode 100644 index 0000000..d1b8da6 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/need_test.go @@ -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") + } +} diff --git a/backend/internal/adapter/primary/http/v1/privacy.go b/backend/internal/adapter/primary/http/v1/privacy.go new file mode 100644 index 0000000..d9ac3d8 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/privacy.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/privacy_test.go b/backend/internal/adapter/primary/http/v1/privacy_test.go new file mode 100644 index 0000000..2ee5130 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/privacy_test.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/support.go b/backend/internal/adapter/primary/http/v1/support.go new file mode 100644 index 0000000..c34a004 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/support.go @@ -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 +} diff --git a/backend/internal/adapter/primary/http/v1/support_test.go b/backend/internal/adapter/primary/http/v1/support_test.go new file mode 100644 index 0000000..fc0d01f --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/support_test.go @@ -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) diff --git a/backend/internal/adapter/secondary/postgres/assessment_attempt.go b/backend/internal/adapter/secondary/postgres/assessment_attempt.go new file mode 100644 index 0000000..b43a9e6 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_attempt.go @@ -0,0 +1,1131 @@ +package postgres + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "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 assessmentAttemptConflictCode = "state_conflict" + +var _ outbound.AssessmentAttemptRepository = assessmentAttemptRepository{} + +func (unit *UnitOfWork) AssessmentAttempts() outbound.AssessmentAttemptRepository { + return assessmentAttemptRepository{queries: unit.queries} +} + +type assessmentAttemptRepository struct { + queries *sqlc.Queries +} + +func (repository assessmentAttemptRepository) LockScope( + ctx context.Context, + userID uuid.UUID, + specialization *domain.SpecializationCode, +) error { + const location = "assessmentAttemptRepository.LockScope" + if userID == uuid.Nil || (specialization != nil && !specialization.IsKnown()) { + return fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err := repository.queries.LockAssessmentAttemptScope(ctx, sqlc.LockAssessmentAttemptScopeParams{ + UserID: userID.String(), Specialization: pgNullableAttemptText(specialization), + }); err != nil { + return fmt.Errorf("%s - lock candidate scope: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func (repository assessmentAttemptRepository) GetActiveForSpecialization( + ctx context.Context, + userID uuid.UUID, + specialization domain.SpecializationCode, +) (domain.AssessmentAttempt, bool, error) { + const location = "assessmentAttemptRepository.GetActiveForSpecialization" + if userID == uuid.Nil || !specialization.IsKnown() { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - candidate track is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + row, err := repository.queries.GetActiveAssessmentAttemptForSpecialization(ctx, sqlc.GetActiveAssessmentAttemptForSpecializationParams{ + UserID: pgUUID(userID), Specialization: pgText(string(specialization)), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttempt{}, false, nil + } + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - read active attempt: %w", location, mapAssessmentAttemptError(err)) + } + attempt, err := repository.restoreAttempt(ctx, row) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - restore active attempt: %w", location, err) + } + return attempt, true, nil +} + +func (repository assessmentAttemptRepository) GetActiveTraining( + ctx context.Context, + userID uuid.UUID, +) (domain.AssessmentAttempt, bool, error) { + const location = "assessmentAttemptRepository.GetActiveTraining" + if userID == uuid.Nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - candidate ID is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + row, err := repository.queries.GetActiveTrainingAssessmentAttempt(ctx, pgUUID(userID)) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttempt{}, false, nil + } + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - read active training attempt: %w", location, mapAssessmentAttemptError(err)) + } + attempt, err := repository.restoreAttempt(ctx, row) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - restore active training attempt: %w", location, err) + } + return attempt, true, nil +} + +func (repository assessmentAttemptRepository) GetLatestRootForSpecialization( + ctx context.Context, + userID uuid.UUID, + specialization domain.SpecializationCode, + grade *domain.GradeCode, +) (domain.AssessmentAttempt, bool, error) { + const location = "assessmentAttemptRepository.GetLatestRootForSpecialization" + if userID == uuid.Nil || !specialization.IsKnown() || (grade != nil && !grade.IsKnown()) { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - candidate track is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + row, err := repository.queries.GetLatestRootAssessmentAttempt(ctx, sqlc.GetLatestRootAssessmentAttemptParams{ + UserID: pgUUID(userID), Specialization: pgText(string(specialization)), TargetGrade: pgNullableAttemptText(grade), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttempt{}, false, nil + } + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - read latest root attempt: %w", location, mapAssessmentAttemptError(err)) + } + attempt, err := repository.restoreAttempt(ctx, row) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - restore latest root attempt: %w", location, err) + } + return attempt, true, nil +} + +func (repository assessmentAttemptRepository) CountRootAttemptsSince( + ctx context.Context, + userID uuid.UUID, + specialization *domain.SpecializationCode, + since time.Time, +) (int32, error) { + const location = "assessmentAttemptRepository.CountRootAttemptsSince" + if userID == uuid.Nil || since.IsZero() || (specialization != nil && !specialization.IsKnown()) { + return 0, fmt.Errorf("%s - candidate scope and start time must be valid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + count, err := repository.queries.CountRootAssessmentAttemptsSince(ctx, sqlc.CountRootAssessmentAttemptsSinceParams{ + UserID: pgUUID(userID), Specialization: pgNullableAttemptText(specialization), Since: pgTime(since), + }) + if err != nil { + return 0, fmt.Errorf("%s - count root attempts: %w", location, mapAssessmentAttemptError(err)) + } + if count < 0 || count > math.MaxInt32 { + return 0, fmt.Errorf("%s - stored attempt count exceeds supported range", location) + } + return int32(count), nil +} + +func (repository assessmentAttemptRepository) ListCorrectionChain( + ctx context.Context, + userID uuid.UUID, + specialization domain.SpecializationCode, + rootID domain.AssessmentAttemptID, +) ([]domain.AssessmentAttempt, error) { + const location = "assessmentAttemptRepository.ListCorrectionChain" + if userID == uuid.Nil || !specialization.IsKnown() || rootID.IsZero() { + return nil, fmt.Errorf("%s - candidate track and root ID must be valid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + rows, err := repository.queries.ListAssessmentAttemptChain(ctx, sqlc.ListAssessmentAttemptChainParams{ + UserID: pgUUID(userID), Specialization: pgText(string(specialization)), RootAttemptID: pgUUID(rootID.UUID()), + }) + if err != nil { + return nil, fmt.Errorf("%s - read attempt chain: %w", location, mapAssessmentAttemptError(err)) + } + attempts := make([]domain.AssessmentAttempt, 0, len(rows)) + for _, row := range rows { + attempt, err := repository.restoreAttempt(ctx, row) + if err != nil { + return nil, fmt.Errorf("%s - restore attempt chain: %w", location, err) + } + attempts = append(attempts, attempt) + } + return attempts, nil +} + +func (repository assessmentAttemptRepository) Create(ctx context.Context, attempt domain.AssessmentAttempt) error { + const location = "assessmentAttemptRepository.Create" + if attempt.IsZero() { + return fmt.Errorf("%s - attempt is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + snapshot := attempt.Snapshot() + rootAttemptID := snapshot.RootAttemptID + if rootAttemptID.IsZero() { + // The database owner/root key points training at itself; the domain + // deliberately exposes no correction root for training runs. + rootAttemptID = snapshot.ID + } + params := sqlc.InsertAssessmentAttemptParams{ + ID: pgUUID(snapshot.ID.UUID()), UserID: pgUUID(snapshot.UserID), Kind: string(snapshot.Kind), + Mode: string(snapshot.Mode), State: string(snapshot.State), Outcome: pgNullableAttemptOutcome(snapshot.Outcome), + BankCategory: string(snapshot.BankCategory), Specialization: pgNullableAttemptText(snapshot.Specialization), + TargetGrade: pgNullableAttemptText(snapshot.TargetGrade), TaskLanguage: pgNullableAttemptText(snapshot.TaskLanguage), + RootAttemptID: pgUUID(rootAttemptID.UUID()), + ProductPolicyVersionID: pgUUID(uuid.UUID(snapshot.Versions.ProductPolicyVersionID)), + ProductPolicyVersion: snapshot.Versions.ProductPolicyVersion, + GradingPolicyVersionID: pgNullablePolicyVersionID(snapshot.Versions.GradingPolicyVersionID), + OpeningID: pgNullableUUID(snapshot.Versions.OpeningID), + OpeningManifestSha256: pgNullableAttemptDigest(snapshot.Versions.OpeningManifestHash), + TrainingBindingID: pgNullableUUID(snapshot.Versions.TrainingBindingID), + TrainingManifestSha256: pgNullableAttemptDigest(snapshot.Versions.TrainingManifestHash), + BankVersion: snapshot.Versions.BankVersion, AlgorithmVersion: snapshot.Versions.AlgorithmVersion, + CreatedAt: pgTime(snapshot.CreatedAt), UpdatedAt: pgTime(snapshot.UpdatedAt), ExpiresAt: pgTime(snapshot.ExpiresAt), + ChainDeadline: pgNullableAttemptTime(snapshot.ChainDeadline), IdleTimeoutSeconds: snapshot.IdleTimeoutSeconds, + MaxSessions: snapshot.MaxSessions, SessionsUsed: snapshot.SessionsUsed, + SessionStartedAt: pgTime(snapshot.SessionStartedAt), LastActivityAt: pgTime(snapshot.LastActivityAt), + Version: snapshot.Version, EndedAt: pgNullableAttemptTime(snapshot.EndedAt), + } + if err := repository.queries.InsertAssessmentAttempt(ctx, params); err != nil { + return fmt.Errorf("%s - insert attempt header: %w", location, mapAssessmentAttemptError(err)) + } + bank := assessmentBankRepository{queries: repository.queries, transactional: true} + for _, item := range snapshot.Items { + family, err := bank.GetFamilyVersion(ctx, item.Variant.FamilyKey, item.Variant.FamilyVersion) + if err != nil { + return fmt.Errorf("%s - recheck pinned family: %w", location, outbound.ErrAssessmentSelectionUnavailable) + } + familyHash := family.ContentHash() + if family.ID() != item.Variant.FamilyID || family.Category() != snapshot.BankCategory || + family.Lifecycle() != domain.AssessmentLifecyclePublished || family.ReviewStatus() != domain.AssessmentReviewApproved { + return fmt.Errorf("%s - family changed after selection: %w", location, outbound.ErrAssessmentSelectionUnavailable) + } + variant, err := domain.MarshalAssessmentAttemptVariant(item.Variant) + if err != nil { + return fmt.Errorf("%s - encode frozen variant: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err := repository.queries.InsertAssessmentAttemptItem(ctx, sqlc.InsertAssessmentAttemptItemParams{ + ID: pgUUID(item.ID), AttemptID: pgUUID(snapshot.ID.UUID()), Ordinal: item.Ordinal, + FamilyID: pgUUID(family.ID().UUID()), FamilyKey: string(item.Variant.FamilyKey), + FamilyVersion: item.Variant.FamilyVersion, FamilyContentSha256: familyHash[:], + Variant: variant, Answer: bytes.Clone(item.Answer), AnsweredAt: pgNullableAttemptTime(item.AnsweredAt), + }); err != nil { + return fmt.Errorf("%s - insert frozen item: %w", location, mapAssessmentAttemptError(err)) + } + } + return nil +} + +func (repository assessmentAttemptRepository) SaveCreateOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + outcome outbound.AssessmentAttemptCreateOutcome, +) error { + const location = "assessmentAttemptRepository.SaveCreateOutcome" + var problemCode pgtype.Text + var response []byte + switch outcome.StatusCode { + case 201: + restored, err := domain.RestoreAssessmentAttemptPublicSnapshot(outcome.Response) + if err != nil || outcome.ProblemCode != "" { + return fmt.Errorf("%s - creation response is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + encoded, err := json.Marshal(restored) + if err != nil { + return fmt.Errorf("%s - encode creation response: %w", location, domain.ErrInvalidAssessmentAttempt) + } + response = encoded + case 409: + if outcome.ProblemCode != assessmentAttemptConflictCode || !outcome.Response.ID.IsZero() { + return fmt.Errorf("%s - conflict response is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + problemCode = pgText(assessmentAttemptConflictCode) + default: + return fmt.Errorf("%s - response status is not allowlisted: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err := repository.queries.InsertAssessmentAttemptIdempotencyOutcome(ctx, sqlc.InsertAssessmentAttemptIdempotencyOutcomeParams{ + ScopeHash: scope[:], Operation: "create", StatusCode: outcome.StatusCode, + ProblemCode: problemCode, ResponseSnapshot: response, PendingItemIds: []pgtype.UUID{}, + }); err != nil { + return fmt.Errorf("%s - store immutable response: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func (repository assessmentAttemptRepository) DeleteExpiredOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, +) error { + const location = "assessmentAttemptRepository.DeleteExpiredOutcome" + if err := repository.queries.DeleteAssessmentAttemptIdempotencyOutcome(ctx, scope[:]); err != nil { + return fmt.Errorf("%s - remove previous-window response: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func (repository assessmentAttemptRepository) GetCreateOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, +) (outbound.AssessmentAttemptCreateOutcome, error) { + const location = "assessmentAttemptRepository.GetCreateOutcome" + row, err := repository.queries.GetAssessmentAttemptIdempotencyOutcome(ctx, scope[:]) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - select replay response: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + if row.Operation != "create" { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - stored operation does not match: %w", location, domain.ErrInvalidAssessmentAttempt) + } + outcome := outbound.AssessmentAttemptCreateOutcome{StatusCode: row.StatusCode} + switch row.StatusCode { + case 201: + encoded, ok := assessmentAttemptOutcomeSnapshotText(row.ResponseSnapshot) + if row.ProblemCode.Valid || !ok || encoded == "" { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - stored creation response is incomplete: %w", location, domain.ErrInvalidAssessmentAttempt) + } + snapshot, err := decodeAssessmentAttemptPublicSnapshot(encoded) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - stored creation response is invalid: %w", location, err) + } + outcome.Response = snapshot + case 409: + encoded, ok := assessmentAttemptOutcomeSnapshotText(row.ResponseSnapshot) + if !row.ProblemCode.Valid || row.ProblemCode.String != assessmentAttemptConflictCode || !ok || encoded != "" { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - stored conflict response is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + outcome.ProblemCode = row.ProblemCode.String + default: + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - stored creation status is not allowlisted: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return outcome, nil +} + +func (repository assessmentAttemptRepository) GetForCandidate( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttempt, error) { + const location = "assessmentAttemptRepository.GetForCandidate" + if userID == uuid.Nil || attemptID.IsZero() { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - candidate and attempt IDs must be valid: %w", location, outbound.ErrAssessmentAttemptNotFound) + } + row, err := repository.queries.GetAssessmentAttemptForCandidate(ctx, sqlc.GetAssessmentAttemptForCandidateParams{ + ID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - select owner-scoped attempt: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + return repository.restoreAttempt(ctx, row) +} + +func (repository assessmentAttemptRepository) GetKindForCandidate( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttemptKind, error) { + const location = "assessmentAttemptRepository.GetKindForCandidate" + if userID == uuid.Nil || attemptID.IsZero() { + return "", fmt.Errorf("%s - candidate and attempt IDs must be valid: %w", location, outbound.ErrAssessmentAttemptNotFound) + } + kind, err := repository.queries.GetAssessmentAttemptKindForCandidate(ctx, sqlc.GetAssessmentAttemptKindForCandidateParams{ + ID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if err != nil { + return "", fmt.Errorf("%s - select owner-scoped attempt kind: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + result := domain.AssessmentAttemptKind(kind) + if result != domain.AssessmentAttemptKindRoot && result != domain.AssessmentAttemptKindCorrective && + result != domain.AssessmentAttemptKindDemoExpress { + return "", fmt.Errorf("%s - stored attempt kind is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return result, nil +} + +func (repository assessmentAttemptRepository) GetForCandidateForUpdate( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttempt, error) { + const location = "assessmentAttemptRepository.GetForCandidateForUpdate" + if userID == uuid.Nil || attemptID.IsZero() { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - candidate and attempt IDs must be valid: %w", location, outbound.ErrAssessmentAttemptNotFound) + } + row, err := repository.queries.LockAssessmentAttemptForCandidate(ctx, sqlc.LockAssessmentAttemptForCandidateParams{ + ID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + return repository.restoreAttempt(ctx, row) +} + +func (repository assessmentAttemptRepository) StartOrResumeSession( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, + expectedVersion int64, + at time.Time, +) (domain.AssessmentAttempt, bool, error) { + const location = "assessmentAttemptRepository.StartOrResumeSession" + if userID == uuid.Nil || attemptID.IsZero() || at.IsZero() { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - candidate, attempt, and time must be valid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + row, err := repository.queries.LockAssessmentAttemptForCandidate(ctx, sqlc.LockAssessmentAttemptForCandidateParams{ + ID: pgUUID(attemptID.UUID()), UserID: pgUUID(userID), + }) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + current, err := repository.restoreAttempt(ctx, row) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - restore locked attempt: %w", location, err) + } + next, changed, err := current.StartOrResumeSession(expectedVersion, at) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - apply session transition: %w", location, mapAssessmentAttemptDomainError(err)) + } + if !changed { + return current, false, nil + } + snapshot := next.Snapshot() + updated, err := repository.queries.UpdateAssessmentAttemptSession(ctx, sqlc.UpdateAssessmentAttemptSessionParams{ + State: string(snapshot.State), Outcome: pgNullableAttemptOutcome(snapshot.Outcome), UpdatedAt: pgTime(snapshot.UpdatedAt), + SessionsUsed: snapshot.SessionsUsed, SessionStartedAt: pgTime(snapshot.SessionStartedAt), + LastActivityAt: pgTime(snapshot.LastActivityAt), Version: snapshot.Version, + EndedAt: pgNullableAttemptTime(snapshot.EndedAt), ID: pgUUID(snapshot.ID.UUID()), + UserID: pgUUID(userID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - update session lost the version race: %w", location, outbound.ErrAssessmentAttemptVersionConflict) + } + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - persist session transition: %w", location, mapAssessmentAttemptError(err)) + } + if updated.Version != snapshot.Version || !updated.UpdatedAt.Time.Equal(snapshot.UpdatedAt) || updated.State != string(snapshot.State) { + return domain.AssessmentAttempt{}, false, fmt.Errorf("%s - persisted session differs from transition: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return next, true, nil +} + +func (repository assessmentAttemptRepository) SaveSessionOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + response domain.AssessmentAttemptPublicSnapshot, +) error { + const location = "assessmentAttemptRepository.SaveSessionOutcome" + restored, err := domain.RestoreAssessmentAttemptPublicSnapshot(response) + if err != nil { + return fmt.Errorf("%s - session response is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + encoded, err := json.Marshal(restored) + if err != nil { + return fmt.Errorf("%s - encode session response: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err := repository.queries.InsertAssessmentAttemptIdempotencyOutcome(ctx, sqlc.InsertAssessmentAttemptIdempotencyOutcomeParams{ + ScopeHash: scope[:], Operation: "session", StatusCode: 200, ResponseSnapshot: encoded, + PendingItemIds: []pgtype.UUID{}, + }); err != nil { + return fmt.Errorf("%s - store immutable response: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func (repository assessmentAttemptRepository) GetSessionOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, +) (domain.AssessmentAttemptPublicSnapshot, error) { + const location = "assessmentAttemptRepository.GetSessionOutcome" + row, err := repository.queries.GetAssessmentAttemptIdempotencyOutcome(ctx, scope[:]) + if err != nil { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - select replay response: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + encoded, ok := assessmentAttemptOutcomeSnapshotText(row.ResponseSnapshot) + if row.Operation != "session" || row.StatusCode != 200 || row.ProblemCode.Valid || !ok || encoded == "" { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - stored session response is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return decodeAssessmentAttemptPublicSnapshot(encoded) +} + +func (repository assessmentAttemptRepository) SaveAnswer( + ctx context.Context, + current, next domain.AssessmentAttempt, + itemID uuid.UUID, +) error { + const location = "assessmentAttemptRepository.SaveAnswer" + currentSnapshot, nextItem, err := validateAssessmentAnswerTransition(current, next, itemID) + if err != nil { + return fmt.Errorf("%s - validate answer transition: %w", location, err) + } + if _, err := repository.queries.UpdateAssessmentAttemptItemAnswer(ctx, sqlc.UpdateAssessmentAttemptItemAnswerParams{ + Answer: bytes.Clone(nextItem.Answer), AnsweredAt: pgTime(nextItem.AnsweredAt), + AttemptID: pgUUID(currentSnapshot.ID.UUID()), ItemID: pgUUID(itemID), + }); errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - item answer lost the write race: %w", location, outbound.ErrAssessmentAttemptVersionConflict) + } else if err != nil { + return fmt.Errorf("%s - persist frozen item answer: %w", location, mapAssessmentAttemptError(err)) + } + return repository.SaveTransition(ctx, current, next) +} + +func validateAssessmentAnswerTransition( + current, next domain.AssessmentAttempt, + itemID uuid.UUID, +) (domain.AssessmentAttemptSnapshot, domain.AssessmentAttemptItemSnapshot, error) { + currentSnapshot, nextSnapshot := current.Snapshot(), next.Snapshot() + if current.IsZero() || next.IsZero() || itemID == uuid.Nil || currentSnapshot.ID != nextSnapshot.ID || + currentSnapshot.UserID != nextSnapshot.UserID || nextSnapshot.Version != currentSnapshot.Version+1 { + return domain.AssessmentAttemptSnapshot{}, domain.AssessmentAttemptItemSnapshot{}, domain.ErrInvalidAssessmentAttempt + } + nextItem := assessmentAttemptSnapshotItem(nextSnapshot, itemID) + if nextItem == nil || len(nextItem.Answer) == 0 || nextItem.AnsweredAt.IsZero() { + return domain.AssessmentAttemptSnapshot{}, domain.AssessmentAttemptItemSnapshot{}, domain.ErrInvalidAssessmentAttempt + } + canonical, err := domain.CanonicalAssessmentAttemptAnswer(nextItem.Answer) + if err != nil || !bytes.Equal(canonical, nextItem.Answer) { + return domain.AssessmentAttemptSnapshot{}, domain.AssessmentAttemptItemSnapshot{}, domain.ErrInvalidAssessmentAttempt + } + currentItem := assessmentAttemptSnapshotItem(currentSnapshot, itemID) + if currentItem == nil || len(currentItem.Answer) != 0 { + return domain.AssessmentAttemptSnapshot{}, domain.AssessmentAttemptItemSnapshot{}, domain.ErrInvalidAssessmentAttempt + } + return currentSnapshot, *nextItem, nil +} + +func assessmentAttemptSnapshotItem( + snapshot domain.AssessmentAttemptSnapshot, + itemID uuid.UUID, +) *domain.AssessmentAttemptItemSnapshot { + for index := range snapshot.Items { + if snapshot.Items[index].ID == itemID { + return &snapshot.Items[index] + } + } + return nil +} + +func (repository assessmentAttemptRepository) SaveTransition( + ctx context.Context, + current, next domain.AssessmentAttempt, +) error { + const location = "assessmentAttemptRepository.SaveTransition" + currentSnapshot, nextSnapshot := current.Snapshot(), next.Snapshot() + if current.IsZero() || next.IsZero() || currentSnapshot.ID != nextSnapshot.ID || + currentSnapshot.UserID != nextSnapshot.UserID || nextSnapshot.Version != currentSnapshot.Version+1 { + return fmt.Errorf("%s - transition identity or version is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + updated, err := repository.queries.UpdateAssessmentAttemptTransition(ctx, sqlc.UpdateAssessmentAttemptTransitionParams{ + State: string(nextSnapshot.State), Outcome: pgNullableAttemptOutcome(nextSnapshot.Outcome), + UpdatedAt: pgTime(nextSnapshot.UpdatedAt), LastActivityAt: pgTime(nextSnapshot.LastActivityAt), + Version: nextSnapshot.Version, EndedAt: pgNullableAttemptTime(nextSnapshot.EndedAt), + ID: pgUUID(currentSnapshot.ID.UUID()), UserID: pgUUID(currentSnapshot.UserID), ExpectedVersion: currentSnapshot.Version, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - transition lost the version race: %w", location, outbound.ErrAssessmentAttemptVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - persist lifecycle transition: %w", location, mapAssessmentAttemptError(err)) + } + if updated.Version != nextSnapshot.Version || updated.State != string(nextSnapshot.State) || + !updated.UpdatedAt.Time.Equal(nextSnapshot.UpdatedAt) || !updated.LastActivityAt.Time.Equal(nextSnapshot.LastActivityAt) { + return fmt.Errorf("%s - stored lifecycle transition differs from domain result: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return nil +} + +func (repository assessmentAttemptRepository) SaveResult( + ctx context.Context, + userID uuid.UUID, + result domain.AssessmentAttemptResultSnapshot, +) error { + const location = "assessmentAttemptRepository.SaveResult" + validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result) + if userID == uuid.Nil { + return fmt.Errorf("%s - owner ID is required: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err != nil { + return fmt.Errorf("%s - result snapshot is invalid: %w", location, err) + } + encoded, err := marshalAssessmentAttemptResultDocument(validated) + if err != nil { + return fmt.Errorf("%s - encode result snapshot: %w", location, err) + } + var gradingPolicyID, openingID, trainingBindingID pgtype.UUID + var openingHash, trainingHash []byte + if validated.Pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) { + gradingPolicyID = pgUUID(uuid.UUID(validated.Pins.GradingPolicyVersionID)) + } + if validated.Pins.OpeningID != uuid.Nil { + openingID = pgUUID(validated.Pins.OpeningID) + } + if validated.Pins.TrainingBindingID != uuid.Nil { + trainingBindingID = pgUUID(validated.Pins.TrainingBindingID) + } + if validated.Pins.OpeningManifestHash != [sha256.Size]byte{} { + openingHash = bytes.Clone(validated.Pins.OpeningManifestHash[:]) + } + if validated.Pins.TrainingManifestHash != [sha256.Size]byte{} { + trainingHash = bytes.Clone(validated.Pins.TrainingManifestHash[:]) + } + var passMark pgtype.Int4 + var scoredItems, rawScore, passPoints pgtype.Int2 + if score := validated.BasicScore; score != nil { + scoredItems, err = assessmentSmallint(validated.Rationale.ScoredItems) + if err != nil { + return fmt.Errorf("%s - scored item count exceeds storage range: %w", location, err) + } + rawScore, err = assessmentSmallint(score.Points) + if err != nil { + return fmt.Errorf("%s - raw score exceeds storage range: %w", location, err) + } + passPoints, err = assessmentSmallint(score.PassPoints) + if err != nil { + return fmt.Errorf("%s - pass points exceed storage range: %w", location, err) + } + passMark = pgtype.Int4{Int32: validated.Rationale.PassMarkBasisPoints, Valid: true} + } + if err := repository.queries.InsertAssessmentAttemptResult(ctx, sqlc.InsertAssessmentAttemptResultParams{ + AttemptID: pgUUID(validated.Attempt.ID.UUID()), UserID: pgUUID(userID), + ResultSnapshot: encoded, Kind: string(validated.Attempt.Kind), Mode: string(validated.Attempt.Mode), + Outcome: string(validated.Outcome), ProductPolicyVersionID: pgUUID(uuid.UUID(validated.Pins.ProductPolicyVersionID)), + ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: gradingPolicyID, + OpeningID: openingID, OpeningManifestSha256: openingHash, TrainingBindingID: trainingBindingID, + TrainingManifestSha256: trainingHash, BankVersion: validated.Pins.BankVersion, + AlgorithmVersion: validated.Pins.AlgorithmVersion, RationaleRule: validated.Rationale.Rule, + PassMarkBasisPoints: passMark, ScoredItems: scoredItems, RawScore: rawScore, + PassPoints: passPoints, DecidedAt: pgTime(validated.DecidedAt), + }); err != nil { + return fmt.Errorf("%s - insert immutable result: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func assessmentSmallint(value int32) (pgtype.Int2, error) { + if value < math.MinInt16 || value > math.MaxInt16 { + return pgtype.Int2{}, domain.ErrInvalidAssessmentAttempt + } + return pgtype.Int2{Int16: int16(value), Valid: true}, nil +} + +func (repository assessmentAttemptRepository) GetResult( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttemptResultSnapshot, error) { + const location = "assessmentAttemptRepository.GetResult" + if userID == uuid.Nil || attemptID.IsZero() { + return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - owner and attempt IDs are required: %w", location, domain.ErrInvalidAssessmentAttempt) + } + encoded, err := repository.queries.GetAssessmentAttemptResult(ctx, sqlc.GetAssessmentAttemptResultParams{ + UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - immutable result is missing: %w", location, outbound.ErrAssessmentAttemptResultNotFound) + } + if err != nil { + return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - select immutable result: %w", location, mapAssessmentAttemptError(err)) + } + result, err := decodeAssessmentAttemptResultDocument([]byte(encoded)) + if err != nil || result.Attempt.ID != attemptID { + return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return result, nil +} + +func (repository assessmentAttemptRepository) SaveAnswerOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + outcome outbound.AssessmentAttemptCommandOutcome, +) error { + return repository.saveCommandOutcome(ctx, scope, "answer", outcome) +} + +func (repository assessmentAttemptRepository) GetAnswerOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, +) (outbound.AssessmentAttemptCommandOutcome, error) { + return repository.getCommandOutcome(ctx, scope, "answer") +} + +func (repository assessmentAttemptRepository) SaveFinalizeOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + outcome outbound.AssessmentAttemptCommandOutcome, +) error { + return repository.saveCommandOutcome(ctx, scope, "finalize", outcome) +} + +func (repository assessmentAttemptRepository) GetFinalizeOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, +) (outbound.AssessmentAttemptCommandOutcome, error) { + return repository.getCommandOutcome(ctx, scope, "finalize") +} + +func (repository assessmentAttemptRepository) saveCommandOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + operation string, + outcome outbound.AssessmentAttemptCommandOutcome, +) error { + const location = "assessmentAttemptRepository.saveCommandOutcome" + pendingItemIDs, err := storedPendingItemUUIDs(outcome.PendingItemIDs) + if err != nil || len(outcome.PendingItemIDs) > 0 && (operation != "finalize" || outcome.StatusCode != 409) { + return fmt.Errorf("%s - pending item snapshot is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + problemCode, response, err := assessmentCommandOutcomeForStorage(operation, outcome) + if err != nil { + return fmt.Errorf("%s - validate command response: %w", location, err) + } + if err := repository.queries.InsertAssessmentAttemptIdempotencyOutcome(ctx, sqlc.InsertAssessmentAttemptIdempotencyOutcomeParams{ + ScopeHash: scope[:], Operation: operation, StatusCode: outcome.StatusCode, + ProblemCode: problemCode, ResponseSnapshot: response, PendingItemIds: pendingItemIDs, + }); err != nil { + return fmt.Errorf("%s - store immutable response: %w", location, mapAssessmentAttemptError(err)) + } + return nil +} + +func assessmentCommandOutcomeForStorage( + operation string, + outcome outbound.AssessmentAttemptCommandOutcome, +) (pgtype.Text, []byte, error) { + if operation != "answer" && operation != "finalize" { + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } + switch outcome.StatusCode { + case 200: + return assessmentCommandSuccessForStorage(outcome) + case 404, 409: + return assessmentCommandProblemForStorage(outcome) + default: + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } +} + +func assessmentCommandSuccessForStorage(outcome outbound.AssessmentAttemptCommandOutcome) (pgtype.Text, []byte, error) { + if outcome.ProblemCode != "" { + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } + restored, err := domain.RestoreAssessmentAttemptPublicSnapshot(outcome.Response) + if err != nil { + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } + response, err := json.Marshal(restored) + if err != nil { + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } + return pgtype.Text{}, response, nil +} + +func assessmentCommandProblemForStorage(outcome outbound.AssessmentAttemptCommandOutcome) (pgtype.Text, []byte, error) { + wantProblem := "not_found" + if outcome.StatusCode == 409 { + wantProblem = assessmentAttemptConflictCode + } + if outcome.ProblemCode != wantProblem || !outcome.Response.ID.IsZero() { + return pgtype.Text{}, nil, domain.ErrInvalidAssessmentAttempt + } + return pgText(wantProblem), nil, nil +} + +func (repository assessmentAttemptRepository) getCommandOutcome( + ctx context.Context, + scope outbound.AssessmentAttemptIdempotencyScope, + wantOperation string, +) (outbound.AssessmentAttemptCommandOutcome, error) { + const location = "assessmentAttemptRepository.getCommandOutcome" + row, err := repository.queries.GetAssessmentAttemptIdempotencyOutcome(ctx, scope[:]) + if err != nil { + return outbound.AssessmentAttemptCommandOutcome{}, fmt.Errorf("%s - select replay response: %w", location, mapNoRows(err, outbound.ErrAssessmentAttemptNotFound)) + } + if row.Operation != wantOperation { + return outbound.AssessmentAttemptCommandOutcome{}, fmt.Errorf("%s - stored operation does not match: %w", location, domain.ErrInvalidAssessmentAttempt) + } + pendingItemIDs, err := restoredPendingItemIDs(row.PendingItemIds) + if err != nil || len(pendingItemIDs) > 0 && wantOperation != "finalize" { + return outbound.AssessmentAttemptCommandOutcome{}, fmt.Errorf("%s - stored pending item snapshot is invalid: %w", location, domain.ErrInvalidAssessmentAttempt) + } + outcome, err := assessmentCommandOutcomeFromRow(row, wantOperation, pendingItemIDs) + if err != nil { + return outbound.AssessmentAttemptCommandOutcome{}, fmt.Errorf("%s - stored response is invalid: %w", location, err) + } + return outcome, nil +} + +func assessmentCommandOutcomeFromRow( + row sqlc.GetAssessmentAttemptIdempotencyOutcomeRow, + wantOperation string, + pendingItemIDs []uuid.UUID, +) (outbound.AssessmentAttemptCommandOutcome, error) { + outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: row.StatusCode, PendingItemIDs: pendingItemIDs} + switch row.StatusCode { + case 200: + snapshot, err := assessmentAttemptSuccessFromRow(row, pendingItemIDs) + if err != nil { + return outbound.AssessmentAttemptCommandOutcome{}, err + } + outcome.Response = snapshot + case 404, 409: + problemCode, err := assessmentCommandProblemFromRow(row, wantOperation, pendingItemIDs) + if err != nil { + return outbound.AssessmentAttemptCommandOutcome{}, err + } + outcome.ProblemCode = problemCode + default: + return outbound.AssessmentAttemptCommandOutcome{}, domain.ErrInvalidAssessmentAttempt + } + return outcome, nil +} + +func assessmentAttemptSuccessFromRow( + row sqlc.GetAssessmentAttemptIdempotencyOutcomeRow, + pendingItemIDs []uuid.UUID, +) (domain.AssessmentAttemptPublicSnapshot, error) { + encoded, ok := assessmentAttemptOutcomeSnapshotText(row.ResponseSnapshot) + if row.ProblemCode.Valid || !ok || encoded == "" || len(pendingItemIDs) != 0 { + return domain.AssessmentAttemptPublicSnapshot{}, domain.ErrInvalidAssessmentAttempt + } + return decodeAssessmentAttemptPublicSnapshot(encoded) +} + +func assessmentCommandProblemFromRow( + row sqlc.GetAssessmentAttemptIdempotencyOutcomeRow, + wantOperation string, + pendingItemIDs []uuid.UUID, +) (string, error) { + wantProblem := "not_found" + if row.StatusCode == 409 { + wantProblem = assessmentAttemptConflictCode + } + encoded, ok := assessmentAttemptOutcomeSnapshotText(row.ResponseSnapshot) + if !row.ProblemCode.Valid || row.ProblemCode.String != wantProblem || !ok || encoded != "" || + row.StatusCode == 404 && len(pendingItemIDs) != 0 || row.StatusCode == 409 && wantOperation == "answer" && len(pendingItemIDs) != 0 { + return "", domain.ErrInvalidAssessmentAttempt + } + return wantProblem, nil +} + +func storedPendingItemUUIDs(itemIDs []uuid.UUID) ([]pgtype.UUID, error) { + if len(itemIDs) > 220 { + return nil, domain.ErrInvalidAssessmentAttempt + } + seen := make(map[uuid.UUID]struct{}, len(itemIDs)) + stored := make([]pgtype.UUID, 0, len(itemIDs)) + for _, itemID := range itemIDs { + if itemID == uuid.Nil { + return nil, domain.ErrInvalidAssessmentAttempt + } + if _, exists := seen[itemID]; exists { + return nil, domain.ErrInvalidAssessmentAttempt + } + seen[itemID] = struct{}{} + stored = append(stored, pgUUID(itemID)) + } + return stored, nil +} + +func restoredPendingItemIDs(itemIDs []pgtype.UUID) ([]uuid.UUID, error) { + if len(itemIDs) > 220 { + return nil, domain.ErrInvalidAssessmentAttempt + } + seen := make(map[uuid.UUID]struct{}, len(itemIDs)) + restored := make([]uuid.UUID, 0, len(itemIDs)) + for _, itemID := range itemIDs { + if !itemID.Valid { + return nil, domain.ErrInvalidAssessmentAttempt + } + value := itemID.Bytes + if value == uuid.Nil { + return nil, domain.ErrInvalidAssessmentAttempt + } + if _, exists := seen[value]; exists { + return nil, domain.ErrInvalidAssessmentAttempt + } + seen[value] = struct{}{} + restored = append(restored, value) + } + return restored, nil +} + +func (repository assessmentAttemptRepository) restoreAttempt( + ctx context.Context, + row sqlc.AssessmentAttempt, +) (domain.AssessmentAttempt, error) { + const location = "assessmentAttemptRepository.restoreAttempt" + itemRows, err := repository.queries.ListAssessmentAttemptItems(ctx, row.ID) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - select frozen items: %w", location, mapAssessmentAttemptError(err)) + } + snapshot, err := assessmentAttemptSnapshotFromRows(row, itemRows) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - rebuild stored snapshot: %w", location, err) + } + attempt, err := domain.RestoreAssessmentAttempt(snapshot) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - stored snapshot failed domain validation: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return attempt, nil +} + +func assessmentAttemptSnapshotFromRows( + row sqlc.AssessmentAttempt, + itemRows []sqlc.ListAssessmentAttemptItemsRow, +) (domain.AssessmentAttemptSnapshot, error) { + const location = "postgres.assessmentAttemptSnapshotFromRows" + stored, err := requiredAttemptSnapshotFields(row) + if err != nil { + return domain.AssessmentAttemptSnapshot{}, fmt.Errorf("%s - stored fields are invalid: %w", location, err) + } + snapshot := domain.AssessmentAttemptSnapshot{ + ID: domain.AssessmentAttemptID(row.ID.Bytes), UserID: row.UserID.Bytes, + Kind: domain.AssessmentAttemptKind(row.Kind), Mode: domain.AssessmentAttemptMode(row.Mode), + State: domain.AssessmentAttemptState(row.State), Outcome: domain.AssessmentAttemptOutcome(row.Outcome.String), + BankCategory: domain.AssessmentCategory(row.BankCategory), RootAttemptID: domain.AssessmentAttemptID(row.RootAttemptID.Bytes), + Versions: domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes), + ProductPolicyVersion: row.ProductPolicyVersion, + GradingPolicyVersionID: domain.PolicyVersionID(row.GradingPolicyVersionID.Bytes), + OpeningID: row.OpeningID.Bytes, OpeningManifestHash: stored.openingHash, + TrainingBindingID: row.TrainingBindingID.Bytes, TrainingManifestHash: stored.trainingHash, + BankVersion: row.BankVersion, AlgorithmVersion: row.AlgorithmVersion, + }, + CreatedAt: stored.createdAt, UpdatedAt: stored.updatedAt, ExpiresAt: stored.expiresAt, + IdleTimeoutSeconds: row.IdleTimeoutSeconds, MaxSessions: row.MaxSessions, SessionsUsed: row.SessionsUsed, + SessionStartedAt: stored.sessionStartedAt, LastActivityAt: stored.lastActivityAt, Version: row.Version, + } + applyAssessmentAttemptOptionalFields(&snapshot, row) + snapshot.Items, err = assessmentAttemptItemsFromRows(itemRows) + if err != nil { + return domain.AssessmentAttemptSnapshot{}, fmt.Errorf("%s - frozen items are invalid: %w", location, err) + } + return snapshot, nil +} + +type storedAttemptSnapshotFields struct { + createdAt time.Time + updatedAt time.Time + expiresAt time.Time + sessionStartedAt time.Time + lastActivityAt time.Time + openingHash [sha256.Size]byte + trainingHash [sha256.Size]byte +} + +func requiredAttemptSnapshotFields(row sqlc.AssessmentAttempt) (storedAttemptSnapshotFields, error) { + var fields storedAttemptSnapshotFields + timestamps := []struct { + name string + value pgtype.Timestamptz + target *time.Time + }{ + {name: "creation", value: row.CreatedAt, target: &fields.createdAt}, + {name: "update", value: row.UpdatedAt, target: &fields.updatedAt}, + {name: "expiry", value: row.ExpiresAt, target: &fields.expiresAt}, + {name: "session", value: row.SessionStartedAt, target: &fields.sessionStartedAt}, + {name: "activity", value: row.LastActivityAt, target: &fields.lastActivityAt}, + } + for _, timestamp := range timestamps { + value, err := requiredAttemptTime(timestamp.value) + if err != nil { + return storedAttemptSnapshotFields{}, fmt.Errorf("%s time is missing: %w", timestamp.name, domain.ErrInvalidAssessmentAttempt) + } + *timestamp.target = value + } + var err error + fields.openingHash, err = storedAttemptDigest(row.OpeningManifestSha256) + if err != nil { + return storedAttemptSnapshotFields{}, fmt.Errorf("opening hash is invalid: %w", domain.ErrInvalidAssessmentAttempt) + } + fields.trainingHash, err = storedAttemptDigest(row.TrainingManifestSha256) + if err != nil { + return storedAttemptSnapshotFields{}, fmt.Errorf("training hash is invalid: %w", domain.ErrInvalidAssessmentAttempt) + } + return fields, nil +} + +func applyAssessmentAttemptOptionalFields(snapshot *domain.AssessmentAttemptSnapshot, row sqlc.AssessmentAttempt) { + if snapshot.Kind == domain.AssessmentAttemptKindDemoExpress { + snapshot.RootAttemptID = domain.AssessmentAttemptID{} + } + if row.Specialization.Valid { + value := domain.SpecializationCode(row.Specialization.String) + snapshot.Specialization = &value + } + if row.TargetGrade.Valid { + value := domain.GradeCode(row.TargetGrade.String) + snapshot.TargetGrade = &value + } + if row.TaskLanguage.Valid { + value := domain.TaskLanguageCode(row.TaskLanguage.String) + snapshot.TaskLanguage = &value + } + if row.ChainDeadline.Valid { + snapshot.ChainDeadline = row.ChainDeadline.Time + } + if row.EndedAt.Valid { + snapshot.EndedAt = row.EndedAt.Time + } +} + +func assessmentAttemptItemsFromRows( + itemRows []sqlc.ListAssessmentAttemptItemsRow, +) ([]domain.AssessmentAttemptItemSnapshot, error) { + items := make([]domain.AssessmentAttemptItemSnapshot, 0, len(itemRows)) + for _, item := range itemRows { + variant, err := decodeStoredAssessmentVariant(item.Variant) + if err != nil || variant.FamilyID.UUID() != item.FamilyID.Bytes || + variant.FamilyKey != domain.AssessmentFamilyKey(item.FamilyKey) || variant.FamilyVersion != item.FamilyVersion { + return nil, fmt.Errorf("frozen variant identity is invalid: %w", domain.ErrInvalidAssessmentAttempt) + } + itemSnapshot := domain.AssessmentAttemptItemSnapshot{ + ID: item.ID.Bytes, Ordinal: item.Ordinal, Variant: variant, Answer: bytes.Clone(item.Answer), + } + if item.AnsweredAt.Valid { + itemSnapshot.AnsweredAt = item.AnsweredAt.Time + } + items = append(items, itemSnapshot) + } + return items, nil +} + +func decodeStoredAssessmentVariant(encoded string) (domain.AssessmentVariant, error) { + return domain.UnmarshalAssessmentAttemptVariant([]byte(encoded)) +} + +func decodeAssessmentAttemptPublicSnapshot(encoded string) (domain.AssessmentAttemptPublicSnapshot, error) { + const location = "postgres.decodeAssessmentAttemptPublicSnapshot" + decoder := json.NewDecoder(bytes.NewBufferString(encoded)) + decoder.DisallowUnknownFields() + var snapshot domain.AssessmentAttemptPublicSnapshot + if err := decoder.Decode(&snapshot); err != nil { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - decode typed response: %w", location, domain.ErrInvalidAssessmentAttempt) + } + var extra any + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - trailing response data: %w", location, domain.ErrInvalidAssessmentAttempt) + } + restored, err := domain.RestoreAssessmentAttemptPublicSnapshot(snapshot) + if err != nil { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - response failed domain validation: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return restored, nil +} + +func assessmentAttemptOutcomeSnapshotText(value any) (string, bool) { + switch snapshot := value.(type) { + case string: + return snapshot, true + case []byte: + return string(snapshot), true + default: + return "", false + } +} + +func storedAttemptDigest(value []byte) ([sha256.Size]byte, error) { + var result [sha256.Size]byte + if len(value) == 0 { + return result, nil + } + if len(value) != sha256.Size { + return result, domain.ErrInvalidAssessmentAttempt + } + copy(result[:], value) + return result, nil +} + +func requiredAttemptTime(value pgtype.Timestamptz) (time.Time, error) { + if !value.Valid || value.Time.IsZero() { + return time.Time{}, domain.ErrInvalidAssessmentAttempt + } + return value.Time, nil +} + +func pgNullableAttemptText[T ~string](value *T) pgtype.Text { + if value == nil { + return pgtype.Text{} + } + return pgText(string(*value)) +} + +func pgNullableAttemptOutcome(value domain.AssessmentAttemptOutcome) pgtype.Text { + if value == "" { + return pgtype.Text{} + } + return pgText(string(value)) +} + +func pgNullablePolicyVersionID(value domain.PolicyVersionID) pgtype.UUID { + if value.IsZero() { + return pgtype.UUID{} + } + return pgUUID(uuid.UUID(value)) +} + +func pgNullableUUID(value uuid.UUID) pgtype.UUID { + if value == uuid.Nil { + return pgtype.UUID{} + } + return pgUUID(value) +} + +func pgNullableAttemptDigest(value [sha256.Size]byte) []byte { + if value == [sha256.Size]byte{} { + return nil + } + return bytes.Clone(value[:]) +} + +func pgNullableAttemptTime(value time.Time) pgtype.Timestamptz { + if value.IsZero() { + return pgtype.Timestamptz{} + } + return pgTime(value) +} + +func mapAssessmentAttemptDomainError(err error) error { + if errors.Is(err, domain.ErrAssessmentAttemptVersionConflict) { + return outbound.ErrAssessmentAttemptVersionConflict + } + return err +} + +func mapAssessmentAttemptError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return mapAssessmentError(err) + } + constraint := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName} + switch constraint { + case constraintViolation{uniqueViolationCode, "assessment_attempts_one_active_real_specialization"}, + constraintViolation{uniqueViolationCode, "assessment_attempts_one_active_training"}, + constraintViolation{checkViolationCode, "assessment_attempt_root_eligibility"}: + return outbound.ErrAssessmentAttemptConflict + case constraintViolation{checkViolationCode, "assessment_attempt_product_policy_pin"}, + constraintViolation{checkViolationCode, "assessment_attempt_opening_pin"}, + constraintViolation{checkViolationCode, "assessment_attempt_training_binding_pin"}, + constraintViolation{checkViolationCode, "assessment_attempt_item_training_member"}, + constraintViolation{checkViolationCode, "assessment_attempt_item_family_pin"}, + constraintViolation{checkViolationCode, "assessment_attempt_item_family_reviewed"}: + return outbound.ErrAssessmentSelectionUnavailable + default: + return mapAssessmentError(err) + } +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_attempt_availability.go b/backend/internal/adapter/secondary/postgres/assessment_attempt_availability.go new file mode 100644 index 0000000..fd87513 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_attempt_availability.go @@ -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 + } +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_attempt_result.go b/backend/internal/adapter/secondary/postgres/assessment_attempt_result.go new file mode 100644 index 0000000..4391db4 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_attempt_result.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_attempt_result_test.go b/backend/internal/adapter/secondary/postgres/assessment_attempt_result_test.go new file mode 100644 index 0000000..6327744 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_attempt_result_test.go @@ -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") + } +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_availability_catalog.go b/backend/internal/adapter/secondary/postgres/assessment_availability_catalog.go new file mode 100644 index 0000000..abec54e --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_availability_catalog.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_bank_test.go b/backend/internal/adapter/secondary/postgres/assessment_bank_test.go index bf260c1..f0e0b6c 100644 --- a/backend/internal/adapter/secondary/postgres/assessment_bank_test.go +++ b/backend/internal/adapter/secondary/postgres/assessment_bank_test.go @@ -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} diff --git a/backend/internal/adapter/secondary/postgres/assessment_catalog.go b/backend/internal/adapter/secondary/postgres/assessment_catalog.go index 713cac4..6c25ab9 100644 --- a/backend/internal/adapter/secondary/postgres/assessment_catalog.go +++ b/backend/internal/adapter/secondary/postgres/assessment_catalog.go @@ -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) { diff --git a/backend/internal/adapter/secondary/postgres/assessment_signals.go b/backend/internal/adapter/secondary/postgres/assessment_signals.go new file mode 100644 index 0000000..dbb9f4b --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_signals.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/consents.go b/backend/internal/adapter/secondary/postgres/consents.go index 9129b60..33425cf 100644 --- a/backend/internal/adapter/secondary/postgres/consents.go +++ b/backend/internal/adapter/secondary/postgres/consents.go @@ -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, diff --git a/backend/internal/adapter/secondary/postgres/needs.go b/backend/internal/adapter/secondary/postgres/needs.go index 479c7bd..75c5df8 100644 --- a/backend/internal/adapter/secondary/postgres/needs.go +++ b/backend/internal/adapter/secondary/postgres/needs.go @@ -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) } diff --git a/backend/internal/adapter/secondary/postgres/organizations.go b/backend/internal/adapter/secondary/postgres/organizations.go index e461190..1a14d29 100644 --- a/backend/internal/adapter/secondary/postgres/organizations.go +++ b/backend/internal/adapter/secondary/postgres/organizations.go @@ -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. diff --git a/backend/internal/adapter/secondary/postgres/privacy_cohort.go b/backend/internal/adapter/secondary/postgres/privacy_cohort.go new file mode 100644 index 0000000..25d15ac --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/privacy_cohort.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/privacy_settings.go b/backend/internal/adapter/secondary/postgres/privacy_settings.go new file mode 100644 index 0000000..ab0b4ee --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/privacy_settings.go @@ -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}) +} diff --git a/backend/internal/adapter/secondary/postgres/privacy_view.go b/backend/internal/adapter/secondary/postgres/privacy_view.go new file mode 100644 index 0000000..ddec363 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/privacy_view.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_attempts.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_attempts.sql.go new file mode 100644 index 0000000..7c31ddd --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_attempts.sql.go @@ -0,0 +1,1319 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: assessment_attempts.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const countRootAssessmentAttemptsSince = `-- name: CountRootAssessmentAttemptsSince :one +SELECT count(*)::bigint +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 = $1 + AND attempt.kind = 'root' + AND attempt.created_at >= $2::timestamptz + AND ($3::text IS NULL OR attempt.specialization = $3::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +` + +type CountRootAssessmentAttemptsSinceParams struct { + UserID pgtype.UUID + Since pgtype.Timestamptz + Specialization pgtype.Text +} + +// Counts root attempts only; the caller applies the effective policy's +// configured window and the product's approved accounting scope. +func (q *Queries) CountRootAssessmentAttemptsSince(ctx context.Context, arg CountRootAssessmentAttemptsSinceParams) (int64, error) { + row := q.db.QueryRow(ctx, countRootAssessmentAttemptsSince, arg.UserID, arg.Since, arg.Specialization) + var column_1 int64 + err := row.Scan(&column_1) + return column_1, err +} + +const deleteAssessmentAttemptIdempotencyOutcome = `-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec +DELETE FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = $1 +` + +// A newly reserved generic idempotency window can replace an expired typed +// outcome before the new immutable response is inserted. +func (q *Queries) DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error { + _, err := q.db.Exec(ctx, deleteAssessmentAttemptIdempotencyOutcome, scopeHash) + return err +} + +const getActiveAssessmentAttemptForSpecialization = `-- name: GetActiveAssessmentAttemptForSpecialization :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_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 +FOR UPDATE +` + +type GetActiveAssessmentAttemptForSpecializationParams struct { + UserID pgtype.UUID + Specialization pgtype.Text +} + +// Locks the active real attempt after LockAssessmentAttemptScope. +func (q *Queries) GetActiveAssessmentAttemptForSpecialization(ctx context.Context, arg GetActiveAssessmentAttemptForSpecializationParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, getActiveAssessmentAttemptForSpecialization, arg.UserID, arg.Specialization) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const getActiveTrainingAssessmentAttempt = `-- name: GetActiveTrainingAssessmentAttempt :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = $1 + AND kind = 'demo_express' + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') +ORDER BY created_at DESC, id DESC +LIMIT 1 +FOR UPDATE +` + +// Locks the one active express attempt after LockAssessmentAttemptScope. +func (q *Queries) GetActiveTrainingAssessmentAttempt(ctx context.Context, userID pgtype.UUID) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, getActiveTrainingAssessmentAttempt, userID) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const getAssessmentAttemptForCandidate = `-- name: GetAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = $1 AND user_id = $2 +FOR SHARE +` + +type GetAssessmentAttemptForCandidateParams struct { + ID pgtype.UUID + UserID pgtype.UUID +} + +// Returns a full private attempt only to its candidate. +func (q *Queries) GetAssessmentAttemptForCandidate(ctx context.Context, arg GetAssessmentAttemptForCandidateParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, getAssessmentAttemptForCandidate, arg.ID, arg.UserID) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const getAssessmentAttemptIdempotencyOutcome = `-- name: GetAssessmentAttemptIdempotencyOutcome :one +SELECT operation, status_code, problem_code, + CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot, + pending_item_ids +FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = $1 +` + +type GetAssessmentAttemptIdempotencyOutcomeRow struct { + Operation string + StatusCode int16 + ProblemCode pgtype.Text + ResponseSnapshot string + PendingItemIds []pgtype.UUID +} + +func (q *Queries) GetAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentAttemptIdempotencyOutcomeRow, error) { + row := q.db.QueryRow(ctx, getAssessmentAttemptIdempotencyOutcome, scopeHash) + var i GetAssessmentAttemptIdempotencyOutcomeRow + err := row.Scan( + &i.Operation, + &i.StatusCode, + &i.ProblemCode, + &i.ResponseSnapshot, + &i.PendingItemIds, + ) + return i, err +} + +const getAssessmentAttemptKindForCandidate = `-- name: GetAssessmentAttemptKindForCandidate :one +SELECT kind +FROM assessment_attempts +WHERE id = $1 AND user_id = $2 +` + +type GetAssessmentAttemptKindForCandidateParams struct { + ID pgtype.UUID + UserID pgtype.UUID +} + +// Reads the immutable attempt kind without locking the row. Session commands +// use this only to decide whether C3 applies before acquiring the row lock. +func (q *Queries) GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error) { + row := q.db.QueryRow(ctx, getAssessmentAttemptKindForCandidate, arg.ID, arg.UserID) + var kind string + err := row.Scan(&kind) + return kind, err +} + +const getAssessmentAttemptResult = `-- name: GetAssessmentAttemptResult :one +SELECT result_snapshot::text AS result_snapshot +FROM assessment_attempt_results +WHERE user_id = $1 AND attempt_id = $2 +` + +type GetAssessmentAttemptResultParams struct { + UserID pgtype.UUID + AttemptID pgtype.UUID +} + +// Reads a result only for the owning candidate. +func (q *Queries) GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error) { + row := q.db.QueryRow(ctx, getAssessmentAttemptResult, arg.UserID, arg.AttemptID) + var result_snapshot string + err := row.Scan(&result_snapshot) + return result_snapshot, err +} + +const getLatestRootAssessmentAttempt = `-- name: GetLatestRootAssessmentAttempt :one +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 +LEFT JOIN assessment_attempt_results AS result + ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id +WHERE attempt.user_id = $1 + AND attempt.specialization = $2 + AND attempt.kind = 'root' + AND ($3::text IS NULL OR attempt.target_grade = $3::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +ORDER BY attempt.created_at DESC, attempt.id DESC +LIMIT 1 +FOR SHARE OF attempt +` + +type GetLatestRootAssessmentAttemptParams struct { + UserID pgtype.UUID + Specialization pgtype.Text + TargetGrade pgtype.Text +} + +// Reads the latest root in a specialization, optionally restricted to grade. +func (q *Queries) GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, getLatestRootAssessmentAttempt, arg.UserID, arg.Specialization, arg.TargetGrade) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const insertAssessmentAttempt = `-- name: InsertAssessmentAttempt :exec +INSERT INTO assessment_attempts ( + id, + user_id, + kind, + mode, + state, + outcome, + bank_category, + specialization, + target_grade, + task_language, + root_attempt_id, + product_policy_version_id, + product_policy_version, + grading_policy_version_id, + opening_id, + opening_manifest_sha256, + training_binding_id, + training_manifest_sha256, + bank_version, + algorithm_version, + created_at, + updated_at, + expires_at, + chain_deadline, + idle_timeout_seconds, + max_sessions, + sessions_used, + session_started_at, + last_activity_at, + version, + ended_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, + $25, + $26, + $27, + $28, + $29, + $30, + $31 +) +` + +type InsertAssessmentAttemptParams 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 +} + +// Inserts the attempt header. The database guard rechecks the current policy, +// opening or disjoint training binding, and immutable pins. +func (q *Queries) InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error { + _, err := q.db.Exec(ctx, insertAssessmentAttempt, + arg.ID, + arg.UserID, + arg.Kind, + arg.Mode, + arg.State, + arg.Outcome, + arg.BankCategory, + arg.Specialization, + arg.TargetGrade, + arg.TaskLanguage, + arg.RootAttemptID, + arg.ProductPolicyVersionID, + arg.ProductPolicyVersion, + arg.GradingPolicyVersionID, + arg.OpeningID, + arg.OpeningManifestSha256, + arg.TrainingBindingID, + arg.TrainingManifestSha256, + arg.BankVersion, + arg.AlgorithmVersion, + arg.CreatedAt, + arg.UpdatedAt, + arg.ExpiresAt, + arg.ChainDeadline, + arg.IdleTimeoutSeconds, + arg.MaxSessions, + arg.SessionsUsed, + arg.SessionStartedAt, + arg.LastActivityAt, + arg.Version, + arg.EndedAt, + ) + return err +} + +const insertAssessmentAttemptIdempotencyOutcome = `-- name: InsertAssessmentAttemptIdempotencyOutcome :exec +INSERT INTO assessment_attempt_idempotency_outcomes ( + scope_hash, operation, status_code, problem_code, response_snapshot, + response_schema_version, pending_item_ids, created_at +) VALUES ( + $1, $2, $3, + $4, $5, 1, + $6::uuid[], transaction_timestamp() +) +` + +type InsertAssessmentAttemptIdempotencyOutcomeParams struct { + ScopeHash []byte + Operation string + StatusCode int16 + ProblemCode pgtype.Text + ResponseSnapshot []byte + PendingItemIds []pgtype.UUID +} + +func (q *Queries) InsertAssessmentAttemptIdempotencyOutcome(ctx context.Context, arg InsertAssessmentAttemptIdempotencyOutcomeParams) error { + _, err := q.db.Exec(ctx, insertAssessmentAttemptIdempotencyOutcome, + arg.ScopeHash, + arg.Operation, + arg.StatusCode, + arg.ProblemCode, + arg.ResponseSnapshot, + arg.PendingItemIds, + ) + return err +} + +const insertAssessmentAttemptItem = `-- name: InsertAssessmentAttemptItem :exec +INSERT INTO assessment_attempt_items ( + id, + attempt_id, + ordinal, + family_id, + family_key, + family_version, + family_content_sha256, + variant, + answer, + answered_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10 +) +` + +type InsertAssessmentAttemptItemParams 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 +} + +// Stores the immutable generated variant and empty answer slot. +func (q *Queries) InsertAssessmentAttemptItem(ctx context.Context, arg InsertAssessmentAttemptItemParams) error { + _, err := q.db.Exec(ctx, insertAssessmentAttemptItem, + arg.ID, + arg.AttemptID, + arg.Ordinal, + arg.FamilyID, + arg.FamilyKey, + arg.FamilyVersion, + arg.FamilyContentSha256, + arg.Variant, + arg.Answer, + arg.AnsweredAt, + ) + return err +} + +const insertAssessmentAttemptResult = `-- name: InsertAssessmentAttemptResult :exec +INSERT INTO assessment_attempt_results ( + attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome, + product_policy_version_id, product_policy_version, + grading_policy_version_id, opening_id, opening_manifest_sha256, + training_binding_id, training_manifest_sha256, bank_version, algorithm_version, + rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at +) +VALUES ( + $1, $2, $3::jsonb, 1, + $4, $5, $6, + $7, $8, + $9, $10, $11, + $12, $13, + $14, $15, $16, + $17, $18, $19, + $20, $21 +) +` + +type InsertAssessmentAttemptResultParams struct { + AttemptID pgtype.UUID + UserID pgtype.UUID + ResultSnapshot []byte + 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 +} + +// Stores one immutable candidate-visible result with the decision rationale +// and source versions used by its finalized attempt. +func (q *Queries) InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error { + _, err := q.db.Exec(ctx, insertAssessmentAttemptResult, + arg.AttemptID, + arg.UserID, + arg.ResultSnapshot, + arg.Kind, + arg.Mode, + arg.Outcome, + arg.ProductPolicyVersionID, + arg.ProductPolicyVersion, + arg.GradingPolicyVersionID, + arg.OpeningID, + arg.OpeningManifestSha256, + arg.TrainingBindingID, + arg.TrainingManifestSha256, + arg.BankVersion, + arg.AlgorithmVersion, + arg.RationaleRule, + arg.PassMarkBasisPoints, + arg.ScoredItems, + arg.RawScore, + arg.PassPoints, + arg.DecidedAt, + ) + return err +} + +const listAssessmentAttemptChain = `-- name: ListAssessmentAttemptChain :many +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = $1 + AND specialization = $2 + AND (id = $3 OR root_attempt_id = $3) +ORDER BY created_at, id +FOR SHARE +` + +type ListAssessmentAttemptChainParams struct { + UserID pgtype.UUID + Specialization pgtype.Text + RootAttemptID pgtype.UUID +} + +// Reads chain headers in creation order. The use case verifies root eligibility +// and descending target grades in the domain before it creates a correction. +func (q *Queries) ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error) { + rows, err := q.db.Query(ctx, listAssessmentAttemptChain, arg.UserID, arg.Specialization, arg.RootAttemptID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []AssessmentAttempt + for rows.Next() { + var i AssessmentAttempt + if err := rows.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAssessmentAttemptItems = `-- name: ListAssessmentAttemptItems :many +SELECT + id, attempt_id, ordinal, family_id, family_key, family_version, + family_content_sha256, variant::text AS variant, answer, answered_at +FROM assessment_attempt_items +WHERE attempt_id = $1 +ORDER BY ordinal +` + +type ListAssessmentAttemptItemsRow struct { + ID pgtype.UUID + AttemptID pgtype.UUID + Ordinal int32 + FamilyID pgtype.UUID + FamilyKey string + FamilyVersion int32 + FamilyContentSha256 []byte + Variant string + Answer []byte + AnsweredAt pgtype.Timestamptz +} + +// Reads private frozen variants and candidate answer bytes in stable order. +func (q *Queries) ListAssessmentAttemptItems(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAttemptItemsRow, error) { + rows, err := q.db.Query(ctx, listAssessmentAttemptItems, attemptID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAssessmentAttemptItemsRow + for rows.Next() { + var i ListAssessmentAttemptItemsRow + if err := rows.Scan( + &i.ID, + &i.AttemptID, + &i.Ordinal, + &i.FamilyID, + &i.FamilyKey, + &i.FamilyVersion, + &i.FamilyContentSha256, + &i.Variant, + &i.Answer, + &i.AnsweredAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAssessmentTrainingBindingFamilies = `-- name: ListAssessmentTrainingBindingFamilies :many +SELECT + family_id, + ordinal, + family_key, + family_version, + content_sha256 +FROM assessment_training_bank_binding_families +WHERE binding_id = $1 +ORDER BY ordinal +` + +type ListAssessmentTrainingBindingFamiliesRow struct { + FamilyID pgtype.UUID + Ordinal int32 + FamilyKey string + FamilyVersion int32 + ContentSha256 []byte +} + +// Reads the exact family membership pinned by a training binding. +func (q *Queries) ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error) { + rows, err := q.db.Query(ctx, listAssessmentTrainingBindingFamilies, bindingID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAssessmentTrainingBindingFamiliesRow + for rows.Next() { + var i ListAssessmentTrainingBindingFamiliesRow + if err := rows.Scan( + &i.FamilyID, + &i.Ordinal, + &i.FamilyKey, + &i.FamilyVersion, + &i.ContentSha256, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listCurrentAssessmentTrainingBindings = `-- name: ListCurrentAssessmentTrainingBindings :many +SELECT + binding.id, + binding.category, + binding.product_policy_version_id, + binding.item_count, + binding.manifest_sha256, + binding.family_manifest, + policy.version AS product_policy_version +FROM assessment_training_bank_bindings AS binding +JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id +WHERE policy.policy_key = 'product' + AND policy.effective_at <= statement_timestamp() + AND NOT EXISTS ( + SELECT 1 FROM policy_versions AS newer + WHERE newer.policy_key = 'product' + AND newer.effective_at <= statement_timestamp() + AND newer.version > policy.version + ) +ORDER BY binding.category, binding.created_at DESC, binding.id +` + +type ListCurrentAssessmentTrainingBindingsRow struct { + ID pgtype.UUID + Category string + ProductPolicyVersionID pgtype.UUID + ItemCount int32 + ManifestSha256 []byte + FamilyManifest []byte + ProductPolicyVersion int32 +} + +// Lists explicit immutable training bindings for the effective product +// policy. Callers reject more than one matching active binding as ambiguous. +func (q *Queries) ListCurrentAssessmentTrainingBindings(ctx context.Context) ([]ListCurrentAssessmentTrainingBindingsRow, error) { + rows, err := q.db.Query(ctx, listCurrentAssessmentTrainingBindings) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCurrentAssessmentTrainingBindingsRow + for rows.Next() { + var i ListCurrentAssessmentTrainingBindingsRow + if err := rows.Scan( + &i.ID, + &i.Category, + &i.ProductPolicyVersionID, + &i.ItemCount, + &i.ManifestSha256, + &i.FamilyManifest, + &i.ProductPolicyVersion, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockAssessmentAttemptForCandidate = `-- name: LockAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = $1 AND user_id = $2 +FOR UPDATE +` + +type LockAssessmentAttemptForCandidateParams struct { + ID pgtype.UUID + UserID pgtype.UUID +} + +// Locks one owner-scoped attempt while a session command performs its CAS. +func (q *Queries) LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, lockAssessmentAttemptForCandidate, arg.ID, arg.UserID) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const lockAssessmentAttemptScope = `-- name: LockAssessmentAttemptScope :exec +WITH candidate_lock AS MATERIALIZED ( + SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:user:' || $1::text, + 0 + )) +) +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:track:' || $1::text || ':' || + COALESCE($2::text, 'training'), + 0 +)) +FROM candidate_lock +` + +type LockAssessmentAttemptScopeParams struct { + UserID string + Specialization pgtype.Text +} + +// Serializes root quota checks for one candidate before taking its optional +// specialization or training lock. All callers acquire these locks in order. +func (q *Queries) LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error { + _, err := q.db.Exec(ctx, lockAssessmentAttemptScope, arg.UserID, arg.Specialization) + return err +} + +const resolveCurrentAssessmentSelection = `-- name: ResolveCurrentAssessmentSelection :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 + AND ( + ($3::text IS NULL AND cardinality(binding.task_languages) = 0) + OR $3::text = ANY(binding.task_languages) + ) +ORDER BY opening.category +` + +type ResolveCurrentAssessmentSelectionParams struct { + Specialization string + Grade string + TaskLanguage pgtype.Text +} + +type ResolveCurrentAssessmentSelectionRow 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 +} + +// 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. +func (q *Queries) ResolveCurrentAssessmentSelection(ctx context.Context, arg ResolveCurrentAssessmentSelectionParams) ([]ResolveCurrentAssessmentSelectionRow, error) { + rows, err := q.db.Query(ctx, resolveCurrentAssessmentSelection, arg.Specialization, arg.Grade, arg.TaskLanguage) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ResolveCurrentAssessmentSelectionRow + for rows.Next() { + var i ResolveCurrentAssessmentSelectionRow + 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 +} + +const updateAssessmentAttemptItemAnswer = `-- name: UpdateAssessmentAttemptItemAnswer :one +UPDATE assessment_attempt_items +SET answer = $1, answered_at = $2 +WHERE attempt_id = $3 + AND id = $4 + AND answer IS NULL +RETURNING id +` + +type UpdateAssessmentAttemptItemAnswerParams struct { + Answer []byte + AnsweredAt pgtype.Timestamptz + AttemptID pgtype.UUID + ItemID pgtype.UUID +} + +// Stores one final answer before advancing the enclosing attempt version. +// The caller holds the owner-scoped attempt row lock for the surrounding unit. +func (q *Queries) UpdateAssessmentAttemptItemAnswer(ctx context.Context, arg UpdateAssessmentAttemptItemAnswerParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, updateAssessmentAttemptItemAnswer, + arg.Answer, + arg.AnsweredAt, + arg.AttemptID, + arg.ItemID, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const updateAssessmentAttemptSession = `-- name: UpdateAssessmentAttemptSession :one +UPDATE assessment_attempts +SET + state = $1, + outcome = $2, + updated_at = $3, + sessions_used = $4, + session_started_at = $5, + last_activity_at = $6, + version = $7, + ended_at = $8 +WHERE id = $9 + AND user_id = $10 + AND version = $11 +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +` + +type UpdateAssessmentAttemptSessionParams struct { + State string + Outcome pgtype.Text + UpdatedAt pgtype.Timestamptz + SessionsUsed int32 + SessionStartedAt pgtype.Timestamptz + LastActivityAt pgtype.Timestamptz + Version int64 + EndedAt pgtype.Timestamptz + ID pgtype.UUID + UserID pgtype.UUID + ExpectedVersion int64 +} + +// Applies a versioned session transition after the attempt row is locked. +func (q *Queries) UpdateAssessmentAttemptSession(ctx context.Context, arg UpdateAssessmentAttemptSessionParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, updateAssessmentAttemptSession, + arg.State, + arg.Outcome, + arg.UpdatedAt, + arg.SessionsUsed, + arg.SessionStartedAt, + arg.LastActivityAt, + arg.Version, + arg.EndedAt, + arg.ID, + arg.UserID, + arg.ExpectedVersion, + ) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} + +const updateAssessmentAttemptTransition = `-- name: UpdateAssessmentAttemptTransition :one +UPDATE assessment_attempts +SET + state = $1, + outcome = $2, + updated_at = $3, + last_activity_at = $4, + version = $5, + ended_at = $6 +WHERE id = $7 + AND user_id = $8 + AND version = $9 +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +` + +type UpdateAssessmentAttemptTransitionParams struct { + State string + Outcome pgtype.Text + UpdatedAt pgtype.Timestamptz + LastActivityAt pgtype.Timestamptz + Version int64 + EndedAt pgtype.Timestamptz + ID pgtype.UUID + UserID pgtype.UUID + ExpectedVersion int64 +} + +// Applies an answer, expiry, or finalization transition after the attempt row +// is locked. Session limits and all immutable pins remain unchanged. +func (q *Queries) UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error) { + row := q.db.QueryRow(ctx, updateAssessmentAttemptTransition, + arg.State, + arg.Outcome, + arg.UpdatedAt, + arg.LastActivityAt, + arg.Version, + arg.EndedAt, + arg.ID, + arg.UserID, + arg.ExpectedVersion, + ) + var i AssessmentAttempt + err := row.Scan( + &i.ID, + &i.UserID, + &i.Kind, + &i.Mode, + &i.State, + &i.Outcome, + &i.BankCategory, + &i.Specialization, + &i.TargetGrade, + &i.TaskLanguage, + &i.RootAttemptID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.TrainingBindingID, + &i.TrainingManifestSha256, + &i.BankVersion, + &i.AlgorithmVersion, + &i.CreatedAt, + &i.UpdatedAt, + &i.ExpiresAt, + &i.ChainDeadline, + &i.IdleTimeoutSeconds, + &i.MaxSessions, + &i.SessionsUsed, + &i.SessionStartedAt, + &i.LastActivityAt, + &i.Version, + &i.EndedAt, + ) + return i, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_availability.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_availability.sql.go new file mode 100644 index 0000000..5989ca3 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_availability.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_signals.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signals.sql.go new file mode 100644 index 0000000..2c6d77c --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signals.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go index f733510..fabc12e 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/consents.sql.go @@ -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, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 709f4b5..d572434 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -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 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/needs.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/needs.sql.go index 055eff7..154188b 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/needs.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/needs.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go index 394a300..a9936c9 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go @@ -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) diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go index b83e5d0..b845d91 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go @@ -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 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go new file mode 100644 index 0000000..d167627 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index fb3f12a..dfc53da 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -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, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/support_cases.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/support_cases.sql.go new file mode 100644 index 0000000..952e5b4 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/support_cases.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/support_rubrics.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/support_rubrics.sql.go new file mode 100644 index 0000000..52b69da --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/support_rubrics.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/support_cases.go b/backend/internal/adapter/secondary/postgres/support_cases.go new file mode 100644 index 0000000..3002e43 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/support_cases.go @@ -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}) +} diff --git a/backend/internal/adapter/secondary/postgres/support_rubrics.go b/backend/internal/adapter/secondary/postgres/support_rubrics.go new file mode 100644 index 0000000..7307666 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/support_rubrics.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/transactor.go b/backend/internal/adapter/secondary/postgres/transactor.go index 942fb29..0ae1e10 100644 --- a/backend/internal/adapter/secondary/postgres/transactor.go +++ b/backend/internal/adapter/secondary/postgres/transactor.go @@ -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() diff --git a/backend/internal/bootstrap/assessment.go b/backend/internal/bootstrap/assessment.go new file mode 100644 index 0000000..8c2d56d --- /dev/null +++ b/backend/internal/bootstrap/assessment.go @@ -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 +} diff --git a/backend/internal/bootstrap/assessment_signal.go b/backend/internal/bootstrap/assessment_signal.go new file mode 100644 index 0000000..0205da5 --- /dev/null +++ b/backend/internal/bootstrap/assessment_signal.go @@ -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 +} diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index c93467e..8d384b8 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -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 diff --git a/backend/internal/bootstrap/need.go b/backend/internal/bootstrap/need.go new file mode 100644 index 0000000..8534116 --- /dev/null +++ b/backend/internal/bootstrap/need.go @@ -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 +} diff --git a/backend/internal/bootstrap/privacy.go b/backend/internal/bootstrap/privacy.go new file mode 100644 index 0000000..56f9fdc --- /dev/null +++ b/backend/internal/bootstrap/privacy.go @@ -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 +} diff --git a/backend/internal/bootstrap/support.go b/backend/internal/bootstrap/support.go new file mode 100644 index 0000000..926dc6b --- /dev/null +++ b/backend/internal/bootstrap/support.go @@ -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 +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 0ba9402..d674267 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -52,6 +52,11 @@ func initialize( newQuestionnaireHandler, newCatalogHandler, newOrganizationHandler, + newNeedHandler, + newSupportHandler, + newAssessmentHandler, + newAssessmentSignalHandler, + newPrivacyHandler, newSessionSecurity, newRouter, newOutboxRelay, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index c53ffc4..f21cc57 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -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() diff --git a/backend/internal/domain/assessment_answer.go b/backend/internal/domain/assessment_answer.go new file mode 100644 index 0000000..402a0c1 --- /dev/null +++ b/backend/internal/domain/assessment_answer.go @@ -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 +} diff --git a/backend/internal/domain/assessment_answer_test.go b/backend/internal/domain/assessment_answer_test.go new file mode 100644 index 0000000..aa70920 --- /dev/null +++ b/backend/internal/domain/assessment_answer_test.go @@ -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 +} diff --git a/backend/internal/domain/assessment_attempt.go b/backend/internal/domain/assessment_attempt.go new file mode 100644 index 0000000..33ff09f --- /dev/null +++ b/backend/internal/domain/assessment_attempt.go @@ -0,0 +1,1307 @@ +package domain + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "regexp" + "slices" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ( + // ErrInvalidAssessmentAttempt reports a malformed attempt or stored + // snapshot. Error text never includes task text or a submitted answer. + ErrInvalidAssessmentAttempt = errors.New("invalid assessment attempt") + // ErrAssessmentAttemptVersionConflict reports a command based on a stale + // attempt version. + ErrAssessmentAttemptVersionConflict = errors.New("assessment attempt version changed") + // ErrAssessmentAttemptNotActive reports a work command against an attempt + // that cannot accept more work. + ErrAssessmentAttemptNotActive = errors.New("assessment attempt is not active") +) + +const maxAssessmentAttemptItems = 220 + +var assessmentVersionLabelPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) +var assessmentPublicTaskElementIDPattern = regexp.MustCompile(`^job_[1-9][0-9]{0,1}$`) + +// AssessmentAttemptID identifies one assessment attempt. +type AssessmentAttemptID uuid.UUID + +// NewAssessmentAttemptID returns a time-ordered UUIDv7. +func NewAssessmentAttemptID() (AssessmentAttemptID, error) { + id, err := uuid.NewV7() + if err != nil { + return AssessmentAttemptID{}, fmt.Errorf("domain.NewAssessmentAttemptID - generate ID: %w", err) + } + return AssessmentAttemptID(id), nil +} + +func (id AssessmentAttemptID) UUID() uuid.UUID { return uuid.UUID(id) } +func (id AssessmentAttemptID) String() string { return uuid.UUID(id).String() } +func (id AssessmentAttemptID) IsZero() bool { return uuid.UUID(id) == uuid.Nil } + +// AssessmentAttemptKind distinguishes a root quota attempt, a corrective +// attempt in its chain, and a training-only run. +type AssessmentAttemptKind string + +const ( + AssessmentAttemptKindRoot AssessmentAttemptKind = "root" + AssessmentAttemptKindCorrective AssessmentAttemptKind = "corrective" + AssessmentAttemptKindDemoExpress AssessmentAttemptKind = "demo_express" +) + +// AssessmentAttemptMode is selected by the server and pinned to an attempt. +type AssessmentAttemptMode string + +const ( + AssessmentAttemptModeDemoBasic AssessmentAttemptMode = "demo_basic" + AssessmentAttemptModeAdaptive AssessmentAttemptMode = "adaptive" + AssessmentAttemptModeDemoExpress AssessmentAttemptMode = "demo_express" +) + +// AssessmentAttemptState is the persisted lifecycle state of an attempt. +// The initial attempt flow creates and resumes in-progress attempts; later +// commands add the remaining transitions. +type AssessmentAttemptState string + +const ( + AssessmentAttemptStateInProgress AssessmentAttemptState = "in_progress" + AssessmentAttemptStatePracticePending AssessmentAttemptState = "practice_pending" + AssessmentAttemptStateAdditionalPracticePending AssessmentAttemptState = "additional_practice_pending" + AssessmentAttemptStateReadyToFinalize AssessmentAttemptState = "ready_to_finalize" + AssessmentAttemptStateCompleted AssessmentAttemptState = "completed" + AssessmentAttemptStateExpired AssessmentAttemptState = "expired" + AssessmentAttemptStateInsufficientBank AssessmentAttemptState = "insufficient_bank" +) + +// AssessmentAttemptOutcome is the final decision persisted by the scoring +// command. Only a non-confirming result may continue into a lower-grade chain. +type AssessmentAttemptOutcome string + +const ( + AssessmentAttemptOutcomeConfirmed AssessmentAttemptOutcome = "confirmed" + AssessmentAttemptOutcomeNotConfirmed AssessmentAttemptOutcome = "not_confirmed" + AssessmentAttemptOutcomeNotDetermined AssessmentAttemptOutcome = "not_determined" + AssessmentAttemptOutcomeDemonstration AssessmentAttemptOutcome = "demonstration" +) + +// AssessmentAttemptVersions pins the product policy, assessment bank and +// algorithm versions used to build an attempt. GradingPolicyVersionID is the +// policy referenced by the category opening; the public contract exposes the +// product policy number as policy_version. +type AssessmentAttemptVersions struct { + ProductPolicyVersionID PolicyVersionID + ProductPolicyVersion int32 + GradingPolicyVersionID PolicyVersionID + OpeningID uuid.UUID + OpeningManifestHash [sha256.Size]byte + TrainingBindingID uuid.UUID + TrainingManifestHash [sha256.Size]byte + BankVersion string + AlgorithmVersion string +} + +// AssessmentAttemptItemInput is one generated variant selected for a new +// attempt. Item order in the slice is the frozen order stored with the +// attempt. +type AssessmentAttemptItemInput struct { + Variant AssessmentVariant +} + +// AssessmentAttemptItemSnapshot is the private frozen variant for one item. +// ReferenceAnswer and answer data must never be serialized to a candidate. +type AssessmentAttemptItemSnapshot struct { + ID uuid.UUID + Ordinal int32 + Variant AssessmentVariant + Answer json.RawMessage + AnsweredAt time.Time +} + +// assessmentAttemptVariantDocument preserves the original persisted field +// names while keeping JSON tags off the shared assessment family model. +type assessmentAttemptVariantDocument struct { + FamilyID AssessmentFamilyID `json:"FamilyID"` + FamilyKey AssessmentFamilyKey `json:"FamilyKey"` + FamilyVersion int32 `json:"FamilyVersion"` + Seed VariantSeed `json:"Seed"` + Parameters map[string]int32 `json:"Parameters"` + Statement string `json:"Statement"` + ReferenceAnswer string `json:"ReferenceAnswer"` + AnswerFormat string `json:"AnswerFormat"` + Rubric AssessmentRubric `json:"Rubric"` +} + +func assessmentAttemptVariantDocumentFromVariant(variant AssessmentVariant) assessmentAttemptVariantDocument { + var document assessmentAttemptVariantDocument + document.FamilyID = variant.FamilyID + document.FamilyKey = variant.FamilyKey + document.FamilyVersion = variant.FamilyVersion + document.Seed = variant.Seed + document.Parameters = variant.Parameters + document.Statement = variant.Statement + document.ReferenceAnswer = variant.ReferenceAnswer + document.AnswerFormat = variant.AnswerFormat + document.Rubric = variant.Rubric + return document +} + +func (document assessmentAttemptVariantDocument) variant() AssessmentVariant { + var variant AssessmentVariant + variant.FamilyID = document.FamilyID + variant.FamilyKey = document.FamilyKey + variant.FamilyVersion = document.FamilyVersion + variant.Seed = document.Seed + variant.Parameters = document.Parameters + variant.Statement = document.Statement + variant.ReferenceAnswer = document.ReferenceAnswer + variant.AnswerFormat = document.AnswerFormat + variant.Rubric = document.Rubric + return variant +} + +// MarshalAssessmentAttemptVariant encodes the frozen private variant using +// its established storage field names. +func MarshalAssessmentAttemptVariant(variant AssessmentVariant) ([]byte, error) { + return json.Marshal(assessmentAttemptVariantDocumentFromVariant(variant)) +} + +// UnmarshalAssessmentAttemptVariant strictly decodes one frozen private +// variant from storage. +func UnmarshalAssessmentAttemptVariant(encoded []byte) (AssessmentVariant, error) { + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.DisallowUnknownFields() + var document assessmentAttemptVariantDocument + if err := decoder.Decode(&document); err != nil { + return AssessmentVariant{}, fmt.Errorf("domain.UnmarshalAssessmentAttemptVariant - decode: %w", ErrInvalidAssessmentAttempt) + } + var extra any + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return AssessmentVariant{}, fmt.Errorf("domain.UnmarshalAssessmentAttemptVariant - trailing data: %w", ErrInvalidAssessmentAttempt) + } + return document.variant(), nil +} + +func (item AssessmentAttemptItemSnapshot) String() string { return redactedAssessmentAttempt } +func (item AssessmentAttemptItemSnapshot) GoString() string { return redactedAssessmentAttempt } +func (item AssessmentAttemptItemSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedAssessmentAttempt) +} +func (item AssessmentAttemptItemSnapshot) LogValue() slog.Value { + return slog.GroupValue(slog.Int("ordinal", int(item.Ordinal)), slog.String("item_id", item.ID.String())) +} + +// AssessmentAttemptSnapshot is the persistence projection. Its items include +// reference answers and must be treated as secret bank data by adapters. +type AssessmentAttemptSnapshot struct { + ID AssessmentAttemptID + UserID uuid.UUID + Kind AssessmentAttemptKind + Mode AssessmentAttemptMode + State AssessmentAttemptState + Outcome AssessmentAttemptOutcome + BankCategory AssessmentCategory + Specialization *SpecializationCode + TargetGrade *GradeCode + TaskLanguage *TaskLanguageCode + RootAttemptID AssessmentAttemptID + Versions AssessmentAttemptVersions + CreatedAt time.Time + UpdatedAt time.Time + ExpiresAt time.Time + ChainDeadline time.Time + IdleTimeoutSeconds int32 + MaxSessions int32 + SessionsUsed int32 + SessionStartedAt time.Time + LastActivityAt time.Time + Version int64 + EndedAt time.Time + Items []AssessmentAttemptItemSnapshot +} + +// AssessmentAttemptPublicItem is the allowlisted candidate projection of one +// frozen item. It deliberately omits family identity, seed, parameters, +// rubric, reference answer, and submitted answer. +type AssessmentAttemptPublicItem struct { + ID uuid.UUID `json:"id"` + Sequence int32 `json:"sequence"` + Prompt string `json:"prompt"` + Content AssessmentAttemptPublicItemContent `json:"content"` +} + +// AssessmentAttemptPublicItemContent is an allowlisted candidate-facing +// projection of the formats currently produced by the reviewed bank. +type AssessmentAttemptPublicItemContent struct { + Format string `json:"format"` + Unit *string `json:"unit,omitempty"` + Elements []AssessmentAttemptPublicOption `json:"elements,omitempty"` +} + +// AssessmentAttemptPublicOption is a generated task element, not a family or +// variant identifier. +type AssessmentAttemptPublicOption struct { + ID string `json:"id"` + Text string `json:"text"` +} + +// AssessmentAttemptPublicSnapshot is the typed response snapshot retained for +// idempotent HTTP replay. It contains no owner ID or private grading material. +type AssessmentAttemptPublicSnapshot struct { + ID AssessmentAttemptID `json:"id"` + Version int64 `json:"version"` + Kind AssessmentAttemptKind `json:"kind"` + Mode AssessmentAttemptMode `json:"mode"` + State AssessmentAttemptState `json:"state"` + Specialization *SpecializationCode `json:"specialization"` + TargetGrade *GradeCode `json:"target_grade"` + TaskLanguage *TaskLanguageCode `json:"task_language"` + RootAttemptID *AssessmentAttemptID `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 *AssessmentAttemptPublicItem `json:"current_item"` + Practices []AssessmentAttemptPublicPractice `json:"practices"` +} + +// AssessmentAttemptPublicPractice is the empty, explicit practice projection +// until attempt creation assigns practice items in a later assessment flow. +type AssessmentAttemptPublicPractice struct { + Kind string `json:"kind"` +} + +func (snapshot AssessmentAttemptSnapshot) String() string { return redactedAssessmentAttempt } +func (snapshot AssessmentAttemptSnapshot) GoString() string { return redactedAssessmentAttempt } +func (snapshot AssessmentAttemptSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedAssessmentAttempt) +} +func (snapshot AssessmentAttemptSnapshot) LogValue() slog.Value { + return slog.GroupValue( + slog.String("attempt_id", snapshot.ID.String()), + slog.String("kind", string(snapshot.Kind)), + slog.String("state", string(snapshot.State)), + slog.Int64("version", snapshot.Version), + ) +} + +const redactedAssessmentAttempt = "[redacted assessment attempt]" + +// AssessmentAttempt is one candidate-owned attempt with frozen item variants +// and execution limits. It is immutable by value; transitions return a copy. +type AssessmentAttempt struct { + snapshot AssessmentAttemptSnapshot +} + +// NewAssessmentAttemptInput supplies server-resolved state. The caller must +// authenticate the candidate, resolve an effective policy and reviewed bank, +// and validate questionnaire/catalog constraints before constructing it. +type NewAssessmentAttemptInput struct { + UserID uuid.UUID + Kind AssessmentAttemptKind + BankCategory AssessmentCategory + Specialization *SpecializationCode + TargetGrade *GradeCode + TaskLanguage *TaskLanguageCode + // Chain is the root followed by each corrective attempt in creation order. + // It is required only for corrective attempts and must come from one + // transactionally consistent repository read. + Chain []AssessmentAttempt + Versions AssessmentAttemptVersions + Policy PolicyVersion + CreatedAt time.Time + Items []AssessmentAttemptItemInput +} + +// NewAssessmentAttempt constructs a root, corrective or express attempt and +// freezes the versions, session limits, and generated item variants. A policy +// without explicit attempt settings is deliberately unavailable for starts. +func NewAssessmentAttempt(input NewAssessmentAttemptInput) (AssessmentAttempt, error) { + const location = "domain.NewAssessmentAttempt" + if err := validateNewAssessmentAttemptInput(input); err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - validate input: %w", location, err) + } + policy := input.Policy.Policy().Assessment + settings := AssessmentAttemptPolicy{} + if policy.Attempt != nil { + settings = *policy.Attempt + } + sessions, idleTimeout := settings.MaxSessions, settings.IdleTimeoutSeconds + if input.Kind == AssessmentAttemptKindDemoExpress { + sessions, idleTimeout = policy.Training.MaxSessions, policy.Training.IdleTimeoutSeconds + } + items, err := buildAssessmentAttemptItems(input.Items) + if err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - freeze items: %w", location, err) + } + id, err := NewAssessmentAttemptID() + if err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - assign ID: %w", location, err) + } + createdAt := canonicalAssessmentTime(input.CreatedAt) + snapshot := AssessmentAttemptSnapshot{ + ID: id, + UserID: input.UserID, + BankCategory: input.BankCategory, + State: AssessmentAttemptStateInProgress, + CreatedAt: createdAt, + UpdatedAt: createdAt, + IdleTimeoutSeconds: idleTimeout, + MaxSessions: sessions, + SessionsUsed: 1, + SessionStartedAt: createdAt, + LastActivityAt: createdAt, + Version: 1, + Versions: input.Versions, + Items: items, + } + if err := populateAssessmentAttemptTrack(&snapshot, input, settings, createdAt); err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - validate attempt track: %w", location, err) + } + return RestoreAssessmentAttempt(snapshot) +} + +func validateNewAssessmentAttemptInput(input NewAssessmentAttemptInput) error { + const location = "domain.validateNewAssessmentAttemptInput" + if input.UserID == uuid.Nil || input.CreatedAt.IsZero() { + return fmt.Errorf("%s - user ID and creation time must be set: %w", location, ErrInvalidAssessmentAttempt) + } + if _, err := ParseAssessmentCategory(string(input.BankCategory)); err != nil { + return fmt.Errorf("%s - bank category is invalid: %w", location, ErrInvalidAssessmentAttempt) + } + if !validProductPolicyVersion(input.Policy, input.Versions) { + return fmt.Errorf("%s - product policy version must match the pinned policy: %w", location, ErrInvalidAssessmentAttempt) + } + if !validAttemptVersionLabels(input.Versions) { + return fmt.Errorf("%s - bank and algorithm versions must be pinned: %w", location, ErrInvalidAssessmentAttempt) + } + assessmentPolicy := input.Policy.Policy().Assessment + switch input.Kind { + case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective: + if assessmentPolicy.Attempt == nil { + return fmt.Errorf("%s - policy has no explicit real attempt settings: %w", location, ErrInvalidAssessmentAttempt) + } + case AssessmentAttemptKindDemoExpress: + if assessmentPolicy.Training == nil { + return fmt.Errorf("%s - policy has no explicit training settings: %w", location, ErrInvalidAssessmentAttempt) + } + if len(input.Items) != int(assessmentPolicy.Training.DemoExpressItemCount) { + return fmt.Errorf("%s - express item count does not match the pinned training policy: %w", location, ErrInvalidAssessmentAttempt) + } + default: + return fmt.Errorf("%s - attempt kind is unknown: %w", location, ErrInvalidAssessmentAttempt) + } + if !validVersionPins(input.Kind, input.Versions) { + return fmt.Errorf("%s - version pins do not match the attempt kind: %w", location, ErrInvalidAssessmentAttempt) + } + if len(input.Items) == 0 || len(input.Items) > maxAssessmentAttemptItems { + return fmt.Errorf("%s - attempt must contain 1 to %d frozen items: %w", location, maxAssessmentAttemptItems, ErrInvalidAssessmentAttempt) + } + return nil +} + +func validProductPolicyVersion(policy PolicyVersion, versions AssessmentAttemptVersions) bool { + return !policy.IsZero() && policy.Key() == ProductPolicyKey && !versions.ProductPolicyVersionID.IsZero() && + versions.ProductPolicyVersionID == policy.ID() && versions.ProductPolicyVersion == policy.Version() +} + +func validAttemptVersionLabels(versions AssessmentAttemptVersions) bool { + return assessmentVersionLabelPattern.MatchString(versions.BankVersion) && + assessmentVersionLabelPattern.MatchString(versions.AlgorithmVersion) +} + +func validVersionPins(kind AssessmentAttemptKind, versions AssessmentAttemptVersions) bool { + switch kind { + case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective: + return !versions.GradingPolicyVersionID.IsZero() && versions.OpeningID != uuid.Nil && + !emptyAssessmentDigest(versions.OpeningManifestHash) && versions.TrainingBindingID == uuid.Nil && + emptyAssessmentDigest(versions.TrainingManifestHash) + case AssessmentAttemptKindDemoExpress: + return versions.GradingPolicyVersionID.IsZero() && versions.OpeningID == uuid.Nil && + emptyAssessmentDigest(versions.OpeningManifestHash) && versions.TrainingBindingID != uuid.Nil && + !emptyAssessmentDigest(versions.TrainingManifestHash) + default: + return false + } +} + +func emptyAssessmentDigest(digest [sha256.Size]byte) bool { return digest == [sha256.Size]byte{} } + +func populateAssessmentAttemptTrack( + snapshot *AssessmentAttemptSnapshot, + input NewAssessmentAttemptInput, + settings AssessmentAttemptPolicy, + createdAt time.Time, +) error { + snapshot.Kind = input.Kind + snapshot.Specialization = clonePointer(input.Specialization) + snapshot.TargetGrade = clonePointer(input.TargetGrade) + snapshot.TaskLanguage = clonePointer(input.TaskLanguage) + switch input.Kind { + case AssessmentAttemptKindRoot: + return populateRootAttemptTrack(snapshot, input, settings, createdAt) + case AssessmentAttemptKindCorrective: + return populateCorrectiveAttemptTrack(snapshot, input, settings, createdAt) + case AssessmentAttemptKindDemoExpress: + return populateExpressAttemptTrack(snapshot, input, createdAt) + default: + return fmt.Errorf("domain.populateAssessmentAttemptTrack - attempt kind is unknown: %w", ErrInvalidAssessmentAttempt) + } +} + +func populateRootAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, settings AssessmentAttemptPolicy, createdAt time.Time) error { + const location = "domain.populateRootAttemptTrack" + if len(input.Chain) != 0 || !validRealAssessmentTrack(input.Specialization, input.TargetGrade) || !validTaskLanguage(input.TaskLanguage) { + return fmt.Errorf("%s - root attempt requires specialization and grade and has no parent: %w", location, ErrInvalidAssessmentAttempt) + } + snapshot.Mode = realModeFromPolicy(settings.RealMode) + snapshot.RootAttemptID = snapshot.ID + snapshot.ChainDeadline = createdAt.Add(settings.ChainDeadline.Duration()) + snapshot.ExpiresAt = minTime(createdAt.Add(settings.Lifetime.Duration()), snapshot.ChainDeadline) + return nil +} + +func populateCorrectiveAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, settings AssessmentAttemptPolicy, createdAt time.Time) error { + const location = "domain.populateCorrectiveAttemptTrack" + if len(input.Chain) == 0 || !validRealAssessmentTrack(input.Specialization, input.TargetGrade) || !validTaskLanguage(input.TaskLanguage) { + return fmt.Errorf("%s - corrective attempt requires a root, specialization, and grade: %w", location, ErrInvalidAssessmentAttempt) + } + chain := make([]AssessmentAttemptSnapshot, len(input.Chain)) + for index, attempt := range input.Chain { + chain[index] = attempt.snapshot + } + if !rootCanContinue(input.UserID, input.Specialization, input.TargetGrade, chain, createdAt) { + return fmt.Errorf("%s - corrective attempt does not continue an eligible failed or expired chain for this candidate: %w", location, ErrInvalidAssessmentAttempt) + } + snapshot.Mode = realModeFromPolicy(settings.RealMode) + root := chain[0] + snapshot.RootAttemptID = root.ID + snapshot.ChainDeadline = root.ChainDeadline + snapshot.ExpiresAt = minTime(createdAt.Add(settings.Lifetime.Duration()), root.ChainDeadline) + return nil +} + +func rootCanContinue( + userID uuid.UUID, + specialization *SpecializationCode, + grade *GradeCode, + chain []AssessmentAttemptSnapshot, + createdAt time.Time, +) bool { + if len(chain) == 0 { + return false + } + root := chain[0] + if !validCorrectionRoot(root, userID, specialization, createdAt) { + return false + } + previous := root + for index := 1; index < len(chain); index++ { + current := chain[index] + if !validCorrectionPredecessor(root, previous, current, userID, specialization) { + return false + } + previous = current + } + return lowerGradeFollows(grade, previous.TargetGrade) && !createdAt.Before(previous.UpdatedAt) +} + +func validCorrectionRoot( + root AssessmentAttemptSnapshot, + userID uuid.UUID, + specialization *SpecializationCode, + createdAt time.Time, +) bool { + return root.Kind == AssessmentAttemptKindRoot && root.RootAttemptID == root.ID && root.UserID == userID && + root.Specialization != nil && *root.Specialization == *specialization && validTerminalForCorrection(root) && + !createdAt.IsZero() && createdAt.Before(root.ChainDeadline) +} + +func validCorrectionPredecessor( + root AssessmentAttemptSnapshot, + previous AssessmentAttemptSnapshot, + current AssessmentAttemptSnapshot, + userID uuid.UUID, + specialization *SpecializationCode, +) bool { + return current.Kind == AssessmentAttemptKindCorrective && current.RootAttemptID == root.ID && + current.UserID == userID && current.Specialization != nil && *current.Specialization == *specialization && + current.ChainDeadline.Equal(root.ChainDeadline) && validTerminalForCorrection(current) && + lowerGradeFollows(current.TargetGrade, previous.TargetGrade) && !current.CreatedAt.Before(previous.UpdatedAt) +} + +func lowerGradeFollows(lowerGrade, higherGrade *GradeCode) bool { + return lowerGrade != nil && higherGrade != nil && isLowerGrade(*lowerGrade, *higherGrade) +} + +func validTerminalForCorrection(attempt AssessmentAttemptSnapshot) bool { + switch attempt.State { + case AssessmentAttemptStateExpired: + return attempt.Outcome == "" + case AssessmentAttemptStateCompleted: + return attempt.Outcome == AssessmentAttemptOutcomeNotConfirmed || + attempt.Outcome == AssessmentAttemptOutcomeNotDetermined + case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending, + AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize, + AssessmentAttemptStateInsufficientBank: + return false + default: + return false + } +} + +func populateExpressAttemptTrack(snapshot *AssessmentAttemptSnapshot, input NewAssessmentAttemptInput, createdAt time.Time) error { + const location = "domain.populateExpressAttemptTrack" + if len(input.Chain) != 0 || input.Specialization != nil || input.TargetGrade != nil || input.TaskLanguage != nil { + return fmt.Errorf("%s - express attempt has no category, grade, language, or parent: %w", location, ErrInvalidAssessmentAttempt) + } + training := input.Policy.Policy().Assessment.Training + if training == nil { + return fmt.Errorf("%s - express attempt requires separate training settings: %w", location, ErrInvalidAssessmentAttempt) + } + snapshot.Mode = AssessmentAttemptModeDemoExpress + snapshot.ExpiresAt = createdAt.Add(time.Duration(training.DemoExpressDurationSeconds) * time.Second) + return nil +} + +func validRealAssessmentTrack(specialization *SpecializationCode, grade *GradeCode) bool { + return specialization != nil && specialization.IsKnown() && grade != nil && grade.IsKnown() +} + +func validTaskLanguage(language *TaskLanguageCode) bool { + return language == nil || language.IsKnown() +} + +func realModeFromPolicy(mode AssessmentRealMode) AssessmentAttemptMode { + return AssessmentAttemptMode(mode) +} + +func isLowerGrade(candidate, current GradeCode) bool { + gradeOrder := map[GradeCode]int{GradeIntern: 0, GradeJunior: 1, GradeMiddle: 2, GradeSenior: 3} + candidateRank, candidateOK := gradeOrder[candidate] + currentRank, currentOK := gradeOrder[current] + return candidateOK && currentOK && candidateRank < currentRank +} + +func minTime(left, right time.Time) time.Time { + if left.Before(right) { + return left + } + return right +} + +func buildAssessmentAttemptItems(input []AssessmentAttemptItemInput) ([]AssessmentAttemptItemSnapshot, error) { + const location = "domain.buildAssessmentAttemptItems" + items := make([]AssessmentAttemptItemSnapshot, 0, len(input)) + seenIDs := make(map[uuid.UUID]struct{}, len(input)) + seenFamilies := make(map[AssessmentFamilyKey]struct{}, len(input)) + for index, itemInput := range input { + variant := cloneAssessmentVariant(itemInput.Variant) + if !validFrozenVariant(variant) { + return nil, fmt.Errorf("%s - item %d has invalid generated content: %w", location, index+1, ErrInvalidAssessmentAttempt) + } + if _, exists := seenFamilies[variant.FamilyKey]; exists { + return nil, fmt.Errorf("%s - item families must be unique: %w", location, ErrInvalidAssessmentAttempt) + } + seenFamilies[variant.FamilyKey] = struct{}{} + id, err := uuid.NewV7() + if err != nil { + return nil, fmt.Errorf("%s - assign item ID: %w", location, err) + } + if _, exists := seenIDs[id]; exists { + return nil, fmt.Errorf("%s - generated item ID was repeated: %w", location, ErrInvalidAssessmentAttempt) + } + seenIDs[id] = struct{}{} + items = append(items, AssessmentAttemptItemSnapshot{ID: id, Ordinal: int32(index + 1), Variant: variant}) + } + return items, nil +} + +func validFrozenVariant(variant AssessmentVariant) bool { + if variant.FamilyID.IsZero() || variant.FamilyVersion < 1 || + (variant.AnswerFormat != AnswerFormatInteger && variant.AnswerFormat != AnswerFormatIntegerSequence) || + variant.ReferenceAnswer == "" || !utf8.ValidString(variant.ReferenceAnswer) || + !utf8.ValidString(variant.Statement) || len(variant.Statement) == 0 || len(variant.Statement) > maxStatementBytes || + !validStoredFamilyKey(variant.FamilyKey) || !validStoredVariantRubric(variant.Rubric) { + return false + } + encoded, err := MarshalAssessmentAttemptVariant(variant) + return err == nil && len(encoded) <= maxAssessmentAttemptVariantBytes +} + +const maxAssessmentAttemptVariantBytes = 1 << 20 + +func validStoredFamilyKey(value AssessmentFamilyKey) bool { + parsed, err := ParseAssessmentFamilyKey(string(value)) + return err == nil && parsed == value +} + +func validStoredVariantRubric(rubric AssessmentRubric) bool { + if !utf8.ValidString(rubric.Principle) || + len(rubric.Principle) == 0 || len(rubric.Principle) > maxAssessmentTextLength || + len(rubric.Criteria) == 0 || len(rubric.Criteria) > maxAssessmentRubricCriteria || + rubric.validate("domain.validStoredVariantRubric") != nil { + return false + } + for _, criterion := range rubric.Criteria { + if !assessmentCriterionIDPattern.MatchString(criterion.ID) || !utf8.ValidString(criterion.Description) || + len(criterion.Description) == 0 || len(criterion.Description) > maxAssessmentTextLength { + return false + } + } + return true +} + +func cloneAssessmentVariant(variant AssessmentVariant) AssessmentVariant { + variant.Parameters = maps.Clone(variant.Parameters) + variant.Rubric = variant.Rubric.clone() + return variant +} + +// RestoreAssessmentAttempt validates and clones a stored attempt snapshot. +func RestoreAssessmentAttempt(snapshot AssessmentAttemptSnapshot) (AssessmentAttempt, error) { + const location = "domain.RestoreAssessmentAttempt" + canonicalizeAssessmentAttemptTimes(&snapshot) + if err := validateAssessmentAttemptSnapshot(snapshot); err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - validate snapshot: %w", location, err) + } + answerThrough := snapshot.UpdatedAt + if !snapshot.EndedAt.IsZero() { + answerThrough = minTime(answerThrough, snapshot.EndedAt) + } + items, err := cloneAndValidateAssessmentAttemptItems( + snapshot.Items, snapshot.CreatedAt, answerThrough, snapshot.ExpiresAt, + ) + if err != nil { + return AssessmentAttempt{}, fmt.Errorf("%s - validate items: %w", location, err) + } + snapshot.Specialization = clonePointer(snapshot.Specialization) + snapshot.TargetGrade = clonePointer(snapshot.TargetGrade) + snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage) + snapshot.Items = items + return AssessmentAttempt{snapshot: snapshot}, nil +} + +func canonicalizeAssessmentAttemptTimes(snapshot *AssessmentAttemptSnapshot) { + snapshot.CreatedAt = canonicalAssessmentTime(snapshot.CreatedAt) + snapshot.UpdatedAt = canonicalAssessmentTime(snapshot.UpdatedAt) + snapshot.ExpiresAt = canonicalAssessmentTime(snapshot.ExpiresAt) + snapshot.ChainDeadline = canonicalAssessmentTime(snapshot.ChainDeadline) + snapshot.SessionStartedAt = canonicalAssessmentTime(snapshot.SessionStartedAt) + snapshot.LastActivityAt = canonicalAssessmentTime(snapshot.LastActivityAt) + snapshot.EndedAt = canonicalAssessmentTime(snapshot.EndedAt) + for index := range snapshot.Items { + snapshot.Items[index].AnsweredAt = canonicalAssessmentTime(snapshot.Items[index].AnsweredAt) + } +} + +func canonicalAssessmentTime(value time.Time) time.Time { + if value.IsZero() { + return time.Time{} + } + return time.UnixMicro(value.UTC().UnixMicro()).UTC() +} + +func validateAssessmentAttemptSnapshot(snapshot AssessmentAttemptSnapshot) error { + const location = "domain.validateAssessmentAttemptSnapshot" + if err := validateAttemptSnapshotIdentity(snapshot); err != nil { + return fmt.Errorf("%s - identity: %w", location, err) + } + if err := validateAttemptSnapshotTimes(snapshot); err != nil { + return fmt.Errorf("%s - timestamps: %w", location, err) + } + if err := validateAttemptSnapshotSessions(snapshot); err != nil { + return fmt.Errorf("%s - session limits: %w", location, err) + } + if err := validateAttemptSnapshotVersions(snapshot.Versions); err != nil { + return fmt.Errorf("%s - versions: %w", location, err) + } + if err := validateAssessmentAttemptTrack(snapshot); err != nil { + return fmt.Errorf("%s - track: %w", location, err) + } + if err := validateAttemptSnapshotState(snapshot); err != nil { + return fmt.Errorf("%s - state: %w", location, err) + } + if len(snapshot.Items) == 0 || len(snapshot.Items) > maxAssessmentAttemptItems { + return fmt.Errorf("%s - item count is outside the supported range: %w", location, ErrInvalidAssessmentAttempt) + } + return nil +} + +func validateAttemptSnapshotIdentity(snapshot AssessmentAttemptSnapshot) error { + if snapshot.ID.IsZero() || snapshot.UserID == uuid.Nil || snapshot.Version < 1 { + return fmt.Errorf("attempt ID, user ID, and version must be set: %w", ErrInvalidAssessmentAttempt) + } + return nil +} + +func validateAttemptSnapshotTimes(snapshot AssessmentAttemptSnapshot) error { + if snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt) || + snapshot.SessionStartedAt.Before(snapshot.CreatedAt) || snapshot.LastActivityAt.Before(snapshot.SessionStartedAt) || + snapshot.UpdatedAt.Before(snapshot.LastActivityAt) { + return fmt.Errorf("created, updated, session, and activity times are inconsistent: %w", ErrInvalidAssessmentAttempt) + } + return nil +} + +func validateAttemptSnapshotSessions(snapshot AssessmentAttemptSnapshot) error { + if snapshot.IdleTimeoutSeconds < 60 || snapshot.IdleTimeoutSeconds > maxAssessmentIdleTimeoutSeconds || + snapshot.MaxSessions < 1 || snapshot.MaxSessions > maxAssessmentSessions || + snapshot.SessionsUsed < 1 || snapshot.SessionsUsed > snapshot.MaxSessions { + return fmt.Errorf("session limits are outside supported bounds: %w", ErrInvalidAssessmentAttempt) + } + return nil +} + +func validateAttemptSnapshotVersions(versions AssessmentAttemptVersions) error { + if !validAttemptVersionLabels(versions) || versions.ProductPolicyVersionID.IsZero() || versions.ProductPolicyVersion < 1 { + return fmt.Errorf("policy, bank, or algorithm version is invalid: %w", ErrInvalidAssessmentAttempt) + } + return nil +} + +func validateAttemptSnapshotState(snapshot AssessmentAttemptSnapshot) error { + switch snapshot.State { + case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending, + AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize: + if !snapshot.EndedAt.IsZero() || snapshot.Outcome != "" { + return fmt.Errorf("an active attempt has no end time or outcome: %w", ErrInvalidAssessmentAttempt) + } + if snapshot.State == AssessmentAttemptStateReadyToFinalize && !allAssessmentAttemptItemsAnswered(snapshot.Items) { + return fmt.Errorf("an attempt is ready to finalize only after all required items are answered: %w", ErrInvalidAssessmentAttempt) + } + case AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank: + if !validAttemptEndTime(snapshot) || snapshot.Outcome != "" { + return fmt.Errorf("an expired attempt has an end time: %w", ErrInvalidAssessmentAttempt) + } + case AssessmentAttemptStateCompleted: + if !validAttemptEndTime(snapshot) || !validAssessmentAttemptOutcome(snapshot.Outcome) || + !validAssessmentAttemptOutcomeForKind(snapshot.Kind, snapshot.Outcome) { + return fmt.Errorf("a completed attempt has a valid outcome and end time: %w", ErrInvalidAssessmentAttempt) + } + default: + return fmt.Errorf("attempt state is unknown: %w", ErrInvalidAssessmentAttempt) + } + return nil +} + +func validAssessmentAttemptOutcomeForKind(kind AssessmentAttemptKind, outcome AssessmentAttemptOutcome) bool { + if kind == AssessmentAttemptKindDemoExpress { + return outcome == AssessmentAttemptOutcomeDemonstration + } + return outcome != AssessmentAttemptOutcomeDemonstration +} + +func validAttemptEndTime(snapshot AssessmentAttemptSnapshot) bool { + return !snapshot.EndedAt.IsZero() && !snapshot.EndedAt.Before(snapshot.CreatedAt) && + !snapshot.EndedAt.Before(snapshot.LastActivityAt) && !snapshot.UpdatedAt.Before(snapshot.EndedAt) +} + +func validAssessmentAttemptOutcome(outcome AssessmentAttemptOutcome) bool { + switch outcome { + case AssessmentAttemptOutcomeConfirmed, AssessmentAttemptOutcomeNotConfirmed, AssessmentAttemptOutcomeNotDetermined, + AssessmentAttemptOutcomeDemonstration: + return true + default: + return false + } +} + +func validateAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) error { + const location = "domain.validateAssessmentAttemptTrack" + switch snapshot.Kind { + case AssessmentAttemptKindRoot: + if !validRootAssessmentAttemptTrack(snapshot) { + return fmt.Errorf("%s - root track is inconsistent: %w", location, ErrInvalidAssessmentAttempt) + } + case AssessmentAttemptKindCorrective: + if !validCorrectiveAssessmentAttemptTrack(snapshot) { + return fmt.Errorf("%s - corrective track is inconsistent: %w", location, ErrInvalidAssessmentAttempt) + } + case AssessmentAttemptKindDemoExpress: + if !validExpressAssessmentAttemptTrack(snapshot) { + return fmt.Errorf("%s - express track is inconsistent: %w", location, ErrInvalidAssessmentAttempt) + } + default: + return fmt.Errorf("%s - attempt kind is unknown: %w", location, ErrInvalidAssessmentAttempt) + } + return nil +} + +func validRootAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool { + return validAssessmentCategory(snapshot.BankCategory) && validRealAssessmentTrack(snapshot.Specialization, snapshot.TargetGrade) && validTaskLanguage(snapshot.TaskLanguage) && + snapshot.RootAttemptID == snapshot.ID && validChainDeadlines(snapshot) && validRealAttemptMode(snapshot.Mode) && + validVersionPins(snapshot.Kind, snapshot.Versions) +} + +func validCorrectiveAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool { + return validAssessmentCategory(snapshot.BankCategory) && validRealAssessmentTrack(snapshot.Specialization, snapshot.TargetGrade) && validTaskLanguage(snapshot.TaskLanguage) && + !snapshot.RootAttemptID.IsZero() && snapshot.RootAttemptID != snapshot.ID && validChainDeadlines(snapshot) && + validRealAttemptMode(snapshot.Mode) && validVersionPins(snapshot.Kind, snapshot.Versions) +} + +func validExpressAssessmentAttemptTrack(snapshot AssessmentAttemptSnapshot) bool { + return validAssessmentCategory(snapshot.BankCategory) && snapshot.Specialization == nil && snapshot.TargetGrade == nil && snapshot.TaskLanguage == nil && + snapshot.RootAttemptID.IsZero() && snapshot.ChainDeadline.IsZero() && validAttemptExpiry(snapshot) && + snapshot.Mode == AssessmentAttemptModeDemoExpress && validVersionPins(snapshot.Kind, snapshot.Versions) +} + +func validAssessmentCategory(category AssessmentCategory) bool { + parsed, err := ParseAssessmentCategory(string(category)) + return err == nil && parsed == category +} + +func validChainDeadlines(snapshot AssessmentAttemptSnapshot) bool { + return !snapshot.ChainDeadline.IsZero() && snapshot.ChainDeadline.After(snapshot.CreatedAt) && + validAttemptExpiry(snapshot) && !snapshot.ExpiresAt.After(snapshot.ChainDeadline) +} + +func validAttemptExpiry(snapshot AssessmentAttemptSnapshot) bool { + return !snapshot.ExpiresAt.IsZero() && snapshot.ExpiresAt.After(snapshot.CreatedAt) +} + +func validRealAttemptMode(mode AssessmentAttemptMode) bool { + return mode == AssessmentAttemptModeDemoBasic || mode == AssessmentAttemptModeAdaptive +} + +func cloneAndValidateAssessmentAttemptItems( + items []AssessmentAttemptItemSnapshot, + createdAt time.Time, + updatedAt time.Time, + expiresAt time.Time, +) ([]AssessmentAttemptItemSnapshot, error) { + const location = "domain.cloneAndValidateAssessmentAttemptItems" + result := make([]AssessmentAttemptItemSnapshot, 0, len(items)) + seenIDs := make(map[uuid.UUID]struct{}, len(items)) + seenFamilies := make(map[AssessmentFamilyKey]struct{}, len(items)) + for index, item := range items { + if !validAssessmentAttemptItem(item, index, createdAt, updatedAt, expiresAt) { + return nil, fmt.Errorf("%s - item order, identity, or generated content is invalid: %w", location, ErrInvalidAssessmentAttempt) + } + if _, exists := seenIDs[item.ID]; exists { + return nil, fmt.Errorf("%s - item IDs must be unique: %w", location, ErrInvalidAssessmentAttempt) + } + if _, exists := seenFamilies[item.Variant.FamilyKey]; exists { + return nil, fmt.Errorf("%s - family keys must be unique: %w", location, ErrInvalidAssessmentAttempt) + } + seenIDs[item.ID] = struct{}{} + seenFamilies[item.Variant.FamilyKey] = struct{}{} + item.Variant = cloneAssessmentVariant(item.Variant) + item.Answer = bytes.Clone(item.Answer) + result = append(result, item) + } + return result, nil +} + +func validAssessmentAttemptItem( + item AssessmentAttemptItemSnapshot, + index int, + createdAt time.Time, + updatedAt time.Time, + expiresAt time.Time, +) bool { + if item.ID == uuid.Nil || item.Ordinal < 1 || int(item.Ordinal) != index+1 || !validFrozenVariant(item.Variant) { + return false + } + if len(item.Answer) == 0 { + return item.AnsweredAt.IsZero() + } + canonical, err := CanonicalAssessmentAttemptAnswer(item.Answer) + return err == nil && bytes.Equal(canonical, item.Answer) && + !item.AnsweredAt.IsZero() && !item.AnsweredAt.Before(createdAt) && + !item.AnsweredAt.After(updatedAt) && item.AnsweredAt.Before(expiresAt) +} + +// JSON escaping may use up to six bytes per allowed source-code character. +// Keep headroom for a 65,536-character answer plus its JSON envelope. +const maxAssessmentAttemptAnswerBytes = 512 << 10 + +// CanonicalAssessmentAttemptAnswer validates one answer JSON object and +// returns bounded canonical UTF-8 JSON bytes for bytea storage. PostgreSQL +// jsonb rejects valid strings that decode to U+0000, so answer bytes are not +// stored as jsonb. +func CanonicalAssessmentAttemptAnswer(answer json.RawMessage) (json.RawMessage, error) { + const location = "domain.CanonicalAssessmentAttemptAnswer" + if len(answer) == 0 || len(answer) > maxAssessmentAttemptAnswerBytes || !utf8.Valid(answer) || !json.Valid(answer) { + return nil, fmt.Errorf("%s - answer must be bounded valid JSON: %w", location, ErrInvalidAssessmentAttempt) + } + + decoder := json.NewDecoder(bytes.NewReader(answer)) + decoder.UseNumber() + var object map[string]any + if err := decoder.Decode(&object); err != nil || object == nil { + return nil, fmt.Errorf("%s - answer must be a JSON object: %w", location, ErrInvalidAssessmentAttempt) + } + var extra any + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return nil, fmt.Errorf("%s - answer contains trailing JSON data: %w", location, ErrInvalidAssessmentAttempt) + } + format, ok := object["format"].(string) + if !ok || format == "" { + return nil, fmt.Errorf("%s - answer format is missing: %w", location, ErrInvalidAssessmentAttempt) + } + + canonical, err := json.Marshal(object) + if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes { + return nil, fmt.Errorf("%s - canonical answer exceeds its storage bound: %w", location, ErrInvalidAssessmentAttempt) + } + return json.RawMessage(canonical), nil +} + +func (attempt AssessmentAttempt) IsZero() bool { return attempt.snapshot.ID.IsZero() } +func (attempt AssessmentAttempt) IsActive() bool { + return isAssessmentAttemptActive(attempt.snapshot.State) +} +func (attempt AssessmentAttempt) ID() AssessmentAttemptID { return attempt.snapshot.ID } +func (attempt AssessmentAttempt) UserID() uuid.UUID { return attempt.snapshot.UserID } +func (attempt AssessmentAttempt) Kind() AssessmentAttemptKind { return attempt.snapshot.Kind } +func (attempt AssessmentAttempt) Mode() AssessmentAttemptMode { return attempt.snapshot.Mode } +func (attempt AssessmentAttempt) State() AssessmentAttemptState { return attempt.snapshot.State } +func (attempt AssessmentAttempt) BankCategory() AssessmentCategory { + return attempt.snapshot.BankCategory +} +func (attempt AssessmentAttempt) Version() int64 { return attempt.snapshot.Version } +func (attempt AssessmentAttempt) ExpiresAt() time.Time { return attempt.snapshot.ExpiresAt } +func (attempt AssessmentAttempt) ChainDeadline() time.Time { return attempt.snapshot.ChainDeadline } +func (attempt AssessmentAttempt) RootAttemptID() AssessmentAttemptID { + return attempt.snapshot.RootAttemptID +} +func (attempt AssessmentAttempt) SessionsUsed() int32 { return attempt.snapshot.SessionsUsed } +func (attempt AssessmentAttempt) MaxSessions() int32 { return attempt.snapshot.MaxSessions } +func (attempt AssessmentAttempt) IdleTimeoutSeconds() int32 { + return attempt.snapshot.IdleTimeoutSeconds +} +func (attempt AssessmentAttempt) UpdatedAt() time.Time { return attempt.snapshot.UpdatedAt } + +// Snapshot returns a deep copy for persistence and read projections. +func (attempt AssessmentAttempt) Snapshot() AssessmentAttemptSnapshot { + snapshot := attempt.snapshot + snapshot.Specialization = clonePointer(snapshot.Specialization) + snapshot.TargetGrade = clonePointer(snapshot.TargetGrade) + snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage) + snapshot.Items = slices.Clone(snapshot.Items) + for index := range snapshot.Items { + snapshot.Items[index].Variant = cloneAssessmentVariant(snapshot.Items[index].Variant) + snapshot.Items[index].Answer = bytes.Clone(snapshot.Items[index].Answer) + } + return snapshot +} + +// PublicSnapshot returns only the fields a candidate may receive. It is safe +// to retain as an idempotency response and to serialize at the HTTP boundary. +func (attempt AssessmentAttempt) PublicSnapshot() AssessmentAttemptPublicSnapshot { + snapshot := attempt.snapshot + public := AssessmentAttemptPublicSnapshot{ + ID: attempt.ID(), Version: snapshot.Version, Kind: snapshot.Kind, Mode: snapshot.Mode, + State: snapshot.State, Specialization: clonePointer(snapshot.Specialization), + TargetGrade: clonePointer(snapshot.TargetGrade), TaskLanguage: clonePointer(snapshot.TaskLanguage), + PolicyVersion: snapshot.Versions.ProductPolicyVersion, BankVersion: snapshot.Versions.BankVersion, + AlgorithmVersion: snapshot.Versions.AlgorithmVersion, StartedAt: snapshot.CreatedAt, ExpiresAt: snapshot.ExpiresAt, + MaxItems: boundedAssessmentItemCount(len(snapshot.Items)), + SessionsUsed: snapshot.SessionsUsed, MaxSessions: snapshot.MaxSessions, + IdleTimeout: snapshot.IdleTimeoutSeconds, Practices: []AssessmentAttemptPublicPractice{}, + } + if snapshot.Kind == AssessmentAttemptKindCorrective { + rootID, deadline := snapshot.RootAttemptID, snapshot.ChainDeadline + public.RootAttemptID = &rootID + public.ChainDeadline = &deadline + } + if !snapshot.EndedAt.IsZero() { + finishedAt := snapshot.EndedAt + public.FinishedAt = &finishedAt + } + for _, item := range snapshot.Items { + if len(item.Answer) > 0 { + public.AnsweredItems++ + continue + } + if snapshot.State == AssessmentAttemptStateInProgress && public.CurrentItem == nil { + content, ok := publicItemContent(item.Variant) + if ok { + public.CurrentItem = &AssessmentAttemptPublicItem{ + ID: item.ID, Sequence: item.Ordinal, Prompt: item.Variant.Statement, Content: content, + } + } + } + } + return public +} + +// PendingItemIDs returns the unanswered frozen item IDs in presentation order. +// It is used only for the bounded finalize state-conflict response. +func (attempt AssessmentAttempt) PendingItemIDs() []uuid.UUID { + if attempt.IsZero() { + return nil + } + ids := make([]uuid.UUID, 0, len(attempt.snapshot.Items)) + for _, item := range attempt.snapshot.Items { + if len(item.Answer) == 0 { + ids = append(ids, item.ID) + } + } + return ids +} + +func publicItemContent(variant AssessmentVariant) (AssessmentAttemptPublicItemContent, bool) { + switch variant.AnswerFormat { + case AnswerFormatInteger: + return AssessmentAttemptPublicItemContent{Format: "number"}, true + case AnswerFormatIntegerSequence: + taskCount, ok := variant.Parameters["tasks"] + if !ok || taskCount < 2 || taskCount > 20 { + return AssessmentAttemptPublicItemContent{}, false + } + elements := make([]AssessmentAttemptPublicOption, 0, taskCount) + for task := int32(1); task <= taskCount; task++ { + elements = append(elements, AssessmentAttemptPublicOption{ + ID: fmt.Sprintf("job_%d", task), Text: fmt.Sprintf("%d", task), + }) + } + return AssessmentAttemptPublicItemContent{Format: "order", Elements: elements}, true + default: + return AssessmentAttemptPublicItemContent{}, false + } +} + +// RestoreAssessmentAttemptPublicSnapshot validates the typed allowlisted +// response retained for idempotent replay and returns detached pointer data. +func RestoreAssessmentAttemptPublicSnapshot( + snapshot AssessmentAttemptPublicSnapshot, +) (AssessmentAttemptPublicSnapshot, error) { + const location = "domain.RestoreAssessmentAttemptPublicSnapshot" + snapshot.StartedAt = canonicalAssessmentTime(snapshot.StartedAt) + snapshot.ExpiresAt = canonicalAssessmentTime(snapshot.ExpiresAt) + snapshot.FinishedAt = clonePointer(snapshot.FinishedAt) + if snapshot.FinishedAt != nil { + finishedAt := canonicalAssessmentTime(*snapshot.FinishedAt) + snapshot.FinishedAt = &finishedAt + } + snapshot.ChainDeadline = clonePointer(snapshot.ChainDeadline) + if snapshot.ChainDeadline != nil { + deadline := canonicalAssessmentTime(*snapshot.ChainDeadline) + snapshot.ChainDeadline = &deadline + } + snapshot.Specialization = clonePointer(snapshot.Specialization) + snapshot.TargetGrade = clonePointer(snapshot.TargetGrade) + snapshot.TaskLanguage = clonePointer(snapshot.TaskLanguage) + if snapshot.Practices == nil { + snapshot.Practices = []AssessmentAttemptPublicPractice{} + } + if !validAssessmentAttemptPublicSnapshot(snapshot) { + return AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - snapshot is invalid: %w", location, ErrInvalidAssessmentAttempt) + } + return snapshot, nil +} + +func validAssessmentAttemptPublicSnapshot(snapshot AssessmentAttemptPublicSnapshot) bool { + if !validAssessmentAttemptPublicIdentity(snapshot) || !validAssessmentAttemptPublicProgress(snapshot) { + return false + } + return validAssessmentAttemptPublicTrack(snapshot) && validAssessmentAttemptPublicState(snapshot) && + validAssessmentAttemptPublicCurrentItem(snapshot) +} + +func validAssessmentAttemptPublicIdentity(snapshot AssessmentAttemptPublicSnapshot) bool { + return !snapshot.ID.IsZero() && snapshot.Version >= 1 && snapshot.PolicyVersion >= 1 && + assessmentVersionLabelPattern.MatchString(snapshot.BankVersion) && + assessmentVersionLabelPattern.MatchString(snapshot.AlgorithmVersion) && + !snapshot.StartedAt.IsZero() && !snapshot.ExpiresAt.IsZero() && snapshot.ExpiresAt.After(snapshot.StartedAt) +} + +func validAssessmentAttemptPublicProgress(snapshot AssessmentAttemptPublicSnapshot) bool { + return snapshot.IdleTimeout >= 60 && snapshot.IdleTimeout <= maxAssessmentIdleTimeoutSeconds && + snapshot.MaxSessions >= 1 && snapshot.MaxSessions <= maxAssessmentSessions && + snapshot.SessionsUsed >= 1 && snapshot.SessionsUsed <= snapshot.MaxSessions && + snapshot.MaxItems >= 1 && snapshot.MaxItems <= 100 && + snapshot.AnsweredItems >= 0 && snapshot.AnsweredItems <= snapshot.MaxItems && + len(snapshot.Practices) == 0 +} + +func validAssessmentAttemptPublicCurrentItem(snapshot AssessmentAttemptPublicSnapshot) bool { + if snapshot.CurrentItem == nil { + return snapshot.State != AssessmentAttemptStateInProgress || snapshot.AnsweredItems == snapshot.MaxItems + } + item := snapshot.CurrentItem + return snapshot.State == AssessmentAttemptStateInProgress && snapshot.AnsweredItems < snapshot.MaxItems && + item.ID != uuid.Nil && item.Sequence >= 1 && item.Sequence <= snapshot.MaxItems && + item.Prompt != "" && len(item.Prompt) <= maxStatementBytes && utf8.ValidString(item.Prompt) && + validAssessmentAttemptPublicItemContent(item.Content) +} + +func boundedAssessmentItemCount(count int) int32 { + if count < 0 || count > maxAssessmentAttemptItems { + return 0 + } + return int32(count) +} + +func validAssessmentAttemptPublicTrack(snapshot AssessmentAttemptPublicSnapshot) bool { + switch snapshot.Kind { + case AssessmentAttemptKindRoot: + return validPublicRootTrack(snapshot) + case AssessmentAttemptKindCorrective: + return validPublicCorrectiveTrack(snapshot) + case AssessmentAttemptKindDemoExpress: + return validPublicTrainingTrack(snapshot) + default: + return false + } +} + +func validPublicRootTrack(snapshot AssessmentAttemptPublicSnapshot) bool { + return validPublicRealTrack(snapshot) && snapshot.RootAttemptID == nil && snapshot.ChainDeadline == nil +} + +func validPublicCorrectiveTrack(snapshot AssessmentAttemptPublicSnapshot) bool { + if !validPublicRealTrack(snapshot) || snapshot.RootAttemptID == nil || snapshot.RootAttemptID.IsZero() || + snapshot.ChainDeadline == nil { + return false + } + return snapshot.ChainDeadline.After(snapshot.StartedAt) && !snapshot.ExpiresAt.After(*snapshot.ChainDeadline) +} + +func validPublicTrainingTrack(snapshot AssessmentAttemptPublicSnapshot) bool { + return snapshot.Mode == AssessmentAttemptModeDemoExpress && snapshot.TaskLanguage == nil && + snapshot.Specialization == nil && snapshot.TargetGrade == nil && snapshot.RootAttemptID == nil && + snapshot.ChainDeadline == nil +} + +func validPublicRealTrack(snapshot AssessmentAttemptPublicSnapshot) bool { + return validTaskLanguage(snapshot.TaskLanguage) && snapshot.Specialization != nil && snapshot.Specialization.IsKnown() && + snapshot.TargetGrade != nil && snapshot.TargetGrade.IsKnown() && + (snapshot.Mode == AssessmentAttemptModeDemoBasic || snapshot.Mode == AssessmentAttemptModeAdaptive) +} + +func validAssessmentAttemptPublicState(snapshot AssessmentAttemptPublicSnapshot) bool { + switch snapshot.State { + case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending, + AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize: + return snapshot.FinishedAt == nil + case AssessmentAttemptStateCompleted, AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank: + return snapshot.FinishedAt != nil && !snapshot.FinishedAt.Before(snapshot.StartedAt) + default: + return false + } +} + +func validAssessmentAttemptPublicItemContent(content AssessmentAttemptPublicItemContent) bool { + switch content.Format { + case "number": + return len(content.Elements) == 0 && (content.Unit == nil || *content.Unit != "" && len(*content.Unit) <= 32) + case "order": + if content.Unit != nil || len(content.Elements) < 2 || len(content.Elements) > 20 { + return false + } + seen := make(map[string]struct{}, len(content.Elements)) + for _, element := range content.Elements { + if !assessmentPublicTaskElementIDPattern.MatchString(element.ID) || element.Text == "" || len(element.Text) > 2000 || !utf8.ValidString(element.Text) { + return false + } + if _, exists := seen[element.ID]; exists { + return false + } + seen[element.ID] = struct{}{} + } + return true + default: + return false + } +} + +func (attempt AssessmentAttempt) String() string { return redactedAssessmentAttempt } +func (attempt AssessmentAttempt) GoString() string { return redactedAssessmentAttempt } +func (attempt AssessmentAttempt) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedAssessmentAttempt) +} +func (attempt AssessmentAttempt) LogValue() slog.Value { + return slog.GroupValue( + slog.String("attempt_id", attempt.ID().String()), + slog.String("kind", string(attempt.Kind())), + slog.String("state", string(attempt.State())), + slog.Int64("version", attempt.Version()), + ) +} + +// StartOrResumeSession starts a fresh work session only after the previous one +// became idle. An active-session repeat is a no-op. Reads never call this +// method, so polling cannot consume a session or advance the version. +func (attempt AssessmentAttempt) StartOrResumeSession(expectedVersion int64, at time.Time) (AssessmentAttempt, bool, error) { + const location = "AssessmentAttempt.StartOrResumeSession" + if attempt.IsZero() || at.IsZero() { + return AssessmentAttempt{}, false, fmt.Errorf("%s - invalid attempt or time: %w", location, ErrInvalidAssessmentAttempt) + } + if expectedVersion != attempt.snapshot.Version { + return AssessmentAttempt{}, false, fmt.Errorf("%s - expected version is stale: %w", location, ErrAssessmentAttemptVersionConflict) + } + if !isAssessmentAttemptActive(attempt.snapshot.State) { + return attempt, false, nil + } + if at.Before(attempt.snapshot.LastActivityAt) { + return AssessmentAttempt{}, false, fmt.Errorf("%s - time predates last activity: %w", location, ErrInvalidAssessmentAttempt) + } + // Only in-progress attempts can expire through a session command. Pending + // practice and finalization states need their own lifecycle transition so a + // session request cannot erase a result that another command must resolve. + if attempt.snapshot.State != AssessmentAttemptStateInProgress { + return attempt, false, nil + } + next := attempt.Snapshot() + nextAt := canonicalAssessmentTime(at) + if !nextAt.Before(next.ExpiresAt) || !next.ChainDeadline.IsZero() && !nextAt.Before(next.ChainDeadline) || next.SessionsUsed >= next.MaxSessions && !nextAt.Before(next.LastActivityAt.Add(time.Duration(next.IdleTimeoutSeconds)*time.Second)) { + next.State = AssessmentAttemptStateExpired + next.EndedAt = nextAt + next.UpdatedAt = nextAt + next.Version++ + updated, err := RestoreAssessmentAttempt(next) + return updated, true, err + } + idleAt := next.LastActivityAt.Add(time.Duration(next.IdleTimeoutSeconds) * time.Second) + if nextAt.Before(idleAt) { + return attempt, false, nil + } + next.SessionsUsed++ + next.SessionStartedAt = nextAt + next.LastActivityAt = nextAt + next.UpdatedAt = nextAt + next.Version++ + updated, err := RestoreAssessmentAttempt(next) + return updated, true, err +} + +func isAssessmentAttemptActive(state AssessmentAttemptState) bool { + switch state { + case AssessmentAttemptStateInProgress, AssessmentAttemptStatePracticePending, + AssessmentAttemptStateAdditionalPracticePending, AssessmentAttemptStateReadyToFinalize: + return true + case AssessmentAttemptStateCompleted, AssessmentAttemptStateExpired, AssessmentAttemptStateInsufficientBank: + return false + default: + return false + } +} + +func clonePointer[T any](value *T) *T { + if value == nil { + return nil + } + cloned := *value + return &cloned +} diff --git a/backend/internal/domain/assessment_attempt_test.go b/backend/internal/domain/assessment_attempt_test.go new file mode 100644 index 0000000..abc213e --- /dev/null +++ b/backend/internal/domain/assessment_attempt_test.go @@ -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 } diff --git a/backend/internal/domain/assessment_result.go b/backend/internal/domain/assessment_result.go new file mode 100644 index 0000000..75a8f40 --- /dev/null +++ b/backend/internal/domain/assessment_result.go @@ -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 +} diff --git a/backend/internal/domain/assessment_signal.go b/backend/internal/domain/assessment_signal.go new file mode 100644 index 0000000..9c900eb --- /dev/null +++ b/backend/internal/domain/assessment_signal.go @@ -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 +} diff --git a/backend/internal/domain/assessment_signal_test.go b/backend/internal/domain/assessment_signal_test.go new file mode 100644 index 0000000..a14b071 --- /dev/null +++ b/backend/internal/domain/assessment_signal_test.go @@ -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) + } + } +} diff --git a/backend/internal/domain/candidate_card_access.go b/backend/internal/domain/candidate_card_access.go new file mode 100644 index 0000000..d22cc3a --- /dev/null +++ b/backend/internal/domain/candidate_card_access.go @@ -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 +} diff --git a/backend/internal/domain/candidate_card_access_test.go b/backend/internal/domain/candidate_card_access_test.go new file mode 100644 index 0000000..9c71258 --- /dev/null +++ b/backend/internal/domain/candidate_card_access_test.go @@ -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) + } +} diff --git a/backend/internal/domain/candidate_view.go b/backend/internal/domain/candidate_view.go new file mode 100644 index 0000000..1dde518 --- /dev/null +++ b/backend/internal/domain/candidate_view.go @@ -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 +} diff --git a/backend/internal/domain/candidate_view_source.go b/backend/internal/domain/candidate_view_source.go new file mode 100644 index 0000000..0f37f82 --- /dev/null +++ b/backend/internal/domain/candidate_view_source.go @@ -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 +} diff --git a/backend/internal/domain/candidate_view_test.go b/backend/internal/domain/candidate_view_test.go new file mode 100644 index 0000000..72a8cdf --- /dev/null +++ b/backend/internal/domain/candidate_view_test.go @@ -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 +} diff --git a/backend/internal/domain/need.go b/backend/internal/domain/need.go index 7c04d99..4dd9bc8 100644 --- a/backend/internal/domain/need.go +++ b/backend/internal/domain/need.go @@ -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 } diff --git a/backend/internal/domain/need_response.go b/backend/internal/domain/need_response.go new file mode 100644 index 0000000..158344e --- /dev/null +++ b/backend/internal/domain/need_response.go @@ -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 } diff --git a/backend/internal/domain/need_response_test.go b/backend/internal/domain/need_response_test.go new file mode 100644 index 0000000..74875ce --- /dev/null +++ b/backend/internal/domain/need_response_test.go @@ -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") + } +} diff --git a/backend/internal/domain/need_test.go b/backend/internal/domain/need_test.go index 625d2b7..54a1aac 100644 --- a/backend/internal/domain/need_test.go +++ b/backend/internal/domain/need_test.go @@ -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 { diff --git a/backend/internal/domain/policy.go b/backend/internal/domain/policy.go index 86a151b..dc1f957 100644 --- a/backend/internal/domain/policy.go +++ b/backend/internal/domain/policy.go @@ -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 { diff --git a/backend/internal/domain/policy_attempt_test.go b/backend/internal/domain/policy_attempt_test.go new file mode 100644 index 0000000..5021f37 --- /dev/null +++ b/backend/internal/domain/policy_attempt_test.go @@ -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") + } +} diff --git a/backend/internal/domain/policy_demo.go b/backend/internal/domain/policy_demo.go index d89943a..a784303 100644 --- a/backend/internal/domain/policy_demo.go +++ b/backend/internal/domain/policy_demo.go @@ -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 +} diff --git a/backend/internal/domain/policy_document.go b/backend/internal/domain/policy_document.go index 05430eb..a767e5e 100644 --- a/backend/internal/domain/policy_document.go +++ b/backend/internal/domain/policy_document.go @@ -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") diff --git a/backend/internal/domain/policy_schema_test.go b/backend/internal/domain/policy_schema_test.go new file mode 100644 index 0000000..1497d06 --- /dev/null +++ b/backend/internal/domain/policy_schema_test.go @@ -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 +} diff --git a/backend/internal/domain/policy_support.go b/backend/internal/domain/policy_support.go new file mode 100644 index 0000000..465f0a4 --- /dev/null +++ b/backend/internal/domain/policy_support.go @@ -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 +} diff --git a/backend/internal/domain/policy_test.go b/backend/internal/domain/policy_test.go index afc1d04..0862282 100644 --- a/backend/internal/domain/policy_test.go +++ b/backend/internal/domain/policy_test.go @@ -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) diff --git a/backend/internal/domain/policy_training_test.go b/backend/internal/domain/policy_training_test.go new file mode 100644 index 0000000..c3d0035 --- /dev/null +++ b/backend/internal/domain/policy_training_test.go @@ -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) + } + } +} diff --git a/backend/internal/domain/support_case.go b/backend/internal/domain/support_case.go new file mode 100644 index 0000000..ad52d3a --- /dev/null +++ b/backend/internal/domain/support_case.go @@ -0,0 +1,1470 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "regexp" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ErrInvalidSupportCase = errors.New("invalid support case") + +// SupportCaseFieldError identifies an invalid user-provided field without +// including the submitted value. It matches ErrInvalidSupportCase. +type SupportCaseFieldError struct { + Pointer string + Reason string +} + +func (fieldError *SupportCaseFieldError) Error() string { + return fmt.Sprintf("support case field %s %s", fieldError.Pointer, fieldError.Reason) +} + +func (*SupportCaseFieldError) Unwrap() error { return ErrInvalidSupportCase } + +const ( + maxSupportCaseDescriptionRunes = 4000 + maxSupportCasePublicTextRunes = 4000 + maxSupportCaseEvents = 200 + redactedSupportCase = "[redacted support case]" + redactedSupportCaseEvent = "[redacted support case event]" + redactedSupportCaseDecision = "[redacted support case decision]" +) + +var supportCaseNumberPattern = regexp.MustCompile(`^SC-([0-9]{4})-([0-9]{6,10})$`) + +// SupportCaseID identifies a support case. +type SupportCaseID uuid.UUID + +// NewSupportCaseID returns a time-ordered UUIDv7. +func NewSupportCaseID() (SupportCaseID, error) { + id, err := uuid.NewV7() + if err != nil { + return SupportCaseID{}, fmt.Errorf("domain.NewSupportCaseID - generate ID: %w", err) + } + return SupportCaseID(id), nil +} + +func (id SupportCaseID) UUID() uuid.UUID { return uuid.UUID(id) } +func (id SupportCaseID) String() string { return uuid.UUID(id).String() } +func (id SupportCaseID) IsZero() bool { return uuid.UUID(id) == uuid.Nil } + +// SupportCaseNumber is the immutable public number assigned by storage. +type SupportCaseNumber string + +// ParseSupportCaseNumber validates a number returned by the support-case +// sequence. The number is for display; API paths use SupportCaseID. +func ParseSupportCaseNumber(value string) (SupportCaseNumber, error) { + if !supportCaseNumberPattern.MatchString(value) { + return "", invalidSupportCase("domain.ParseSupportCaseNumber", "number format is invalid") + } + return SupportCaseNumber(value), nil +} + +func (number SupportCaseNumber) String() string { return string(number) } + +func (number SupportCaseNumber) validFor(createdAt time.Time) bool { + matches := supportCaseNumberPattern.FindStringSubmatch(string(number)) + if matches == nil || createdAt.IsZero() { + return false + } + year, err := strconv.Atoi(matches[1]) + return err == nil && year == createdAt.UTC().Year() +} + +// SupportCaseType selects the allowed reference and response target. +type SupportCaseType string + +const ( + SupportCaseTypeSupport SupportCaseType = "support" + SupportCaseTypeComplaint SupportCaseType = "complaint" + SupportCaseTypeGradeAppeal SupportCaseType = "grade_appeal" + SupportCaseTypeAnticheatAppeal SupportCaseType = "anticheat_appeal" + SupportCaseTypeManualAssessment SupportCaseType = "manual_assessment" +) + +func (caseType SupportCaseType) IsKnown() bool { + switch caseType { + case SupportCaseTypeSupport, SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal, + SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment: + return true + default: + return false + } +} + +func (caseType SupportCaseType) routesToExpert() bool { + return caseType == SupportCaseTypeGradeAppeal || caseType == SupportCaseTypeAnticheatAppeal || + caseType == SupportCaseTypeManualAssessment +} + +// SupportCaseStatus is the public processing state of a case. +type SupportCaseStatus string + +const ( + SupportCaseStatusSubmitted SupportCaseStatus = "submitted" + SupportCaseStatusInReview SupportCaseStatus = "in_review" + SupportCaseStatusWaitingForUser SupportCaseStatus = "waiting_for_user" + SupportCaseStatusWaitingExpert SupportCaseStatus = "waiting_expert" + SupportCaseStatusResolved SupportCaseStatus = "resolved" + SupportCaseStatusClosed SupportCaseStatus = "closed" +) + +func (status SupportCaseStatus) IsKnown() bool { + switch status { + case SupportCaseStatusSubmitted, SupportCaseStatusInReview, SupportCaseStatusWaitingForUser, + SupportCaseStatusWaitingExpert, SupportCaseStatusResolved, SupportCaseStatusClosed: + return true + default: + return false + } +} + +func (status SupportCaseStatus) IsTerminal() bool { + return status == SupportCaseStatusResolved || status == SupportCaseStatusClosed +} + +// SupportCaseObjectType is the type of a reference stored with a case. The +// case stores only this value and the identifier, never the referenced data. +type SupportCaseObjectType string + +const ( + SupportCaseObjectAssessmentAttempt SupportCaseObjectType = "assessment_attempt" + SupportCaseObjectOrganization SupportCaseObjectType = "organization" + SupportCaseObjectInvitation SupportCaseObjectType = "invitation" + SupportCaseObjectSupportCase SupportCaseObjectType = "support_case" +) + +func (objectType SupportCaseObjectType) IsKnown() bool { + switch objectType { + case SupportCaseObjectAssessmentAttempt, SupportCaseObjectOrganization, + SupportCaseObjectInvitation, SupportCaseObjectSupportCase: + return true + default: + return false + } +} + +// SupportCaseReference is a private reference to the object a case concerns. +type SupportCaseReference struct { + Type SupportCaseObjectType `json:"type"` + ID uuid.UUID `json:"id"` +} + +func (SupportCaseReference) String() string { return "[support case reference]" } +func (SupportCaseReference) GoString() string { return "[support case reference]" } +func (SupportCaseReference) Format(state fmt.State, _ rune) { + writeRedacted(state, "[support case reference]") +} +func (reference SupportCaseReference) LogValue() slog.Value { + return slog.StringValue(string(reference.Type)) +} + +// SupportCaseAssessmentTarget is the specialization and grade discussed by a +// case. It does not assert that the user has that grade. +type SupportCaseAssessmentTarget struct { + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` +} + +// SupportCaseComplaintReason is the ground of a candidate complaint. +type SupportCaseComplaintReason string + +const ( + SupportComplaintOrganizationConduct SupportCaseComplaintReason = "organization_conduct" + SupportComplaintOfferContent SupportCaseComplaintReason = "offer_content" + SupportComplaintSalaryTermsViolation SupportCaseComplaintReason = "salary_terms_violation" + SupportComplaintDataDisclosure SupportCaseComplaintReason = "data_disclosure" + SupportComplaintOther SupportCaseComplaintReason = "other" +) + +func (reason SupportCaseComplaintReason) IsKnown() bool { + switch reason { + case SupportComplaintOrganizationConduct, SupportComplaintOfferContent, + SupportComplaintSalaryTermsViolation, SupportComplaintDataDisclosure, SupportComplaintOther: + return true + default: + return false + } +} + +// SupportResponseTargetKind labels an operational goal. It is never a legal +// deadline. +type SupportResponseTargetKind string + +const SupportResponseTargetOperationalGoal SupportResponseTargetKind = "operational_goal" + +// SupportResponseTargetSnapshot is the persistence form of a response target. +// The late flag is derived for each read from AnsweredAt or the current time. +type SupportResponseTargetSnapshot struct { + BusinessDays BusinessDays `json:"business_days"` + DueAt time.Time `json:"due_at"` + AnsweredAt *time.Time `json:"answered_at,omitempty"` + PolicyVersion int32 `json:"policy_version"` + CalendarVersion int32 `json:"calendar_version"` +} + +// SupportResponseTarget is an immutable operational target fixed at case +// creation. +type SupportResponseTarget struct { + snapshot SupportResponseTargetSnapshot +} + +func NewSupportResponseTarget(snapshot SupportResponseTargetSnapshot) (SupportResponseTarget, error) { + const location = "domain.NewSupportResponseTarget" + snapshot = cloneSupportResponseTargetSnapshot(snapshot) + if snapshot.BusinessDays < 1 || snapshot.BusinessDays > 60 || snapshot.DueAt.IsZero() || + snapshot.PolicyVersion < 1 || snapshot.CalendarVersion < 1 { + return SupportResponseTarget{}, invalidSupportCase(location, "target days, due time, policy version, and calendar version must be valid") + } + if snapshot.AnsweredAt != nil && snapshot.AnsweredAt.IsZero() { + return SupportResponseTarget{}, invalidSupportCase(location, "answered time must be set when present") + } + return SupportResponseTarget{snapshot: cloneSupportResponseTargetSnapshot(snapshot)}, nil +} + +func (target SupportResponseTarget) Kind() SupportResponseTargetKind { + return SupportResponseTargetOperationalGoal +} + +func (target SupportResponseTarget) BusinessDays() BusinessDays { return target.snapshot.BusinessDays } +func (target SupportResponseTarget) DueAt() time.Time { return target.snapshot.DueAt } +func (target SupportResponseTarget) PolicyVersion() int32 { return target.snapshot.PolicyVersion } +func (target SupportResponseTarget) BusinessCalendarVersion() int32 { + return target.snapshot.CalendarVersion +} + +func (target SupportResponseTarget) AnsweredAt() *time.Time { + return cloneTimePointer(target.snapshot.AnsweredAt) +} + +func (target SupportResponseTarget) IsLate(at time.Time) bool { + if target.IsZero() || at.IsZero() { + return false + } + if target.snapshot.AnsweredAt != nil { + return target.snapshot.AnsweredAt.After(target.snapshot.DueAt) + } + return at.After(target.snapshot.DueAt) +} + +func (target SupportResponseTarget) Snapshot() SupportResponseTargetSnapshot { + return cloneSupportResponseTargetSnapshot(target.snapshot) +} + +func (target SupportResponseTarget) IsZero() bool { return target.snapshot.DueAt.IsZero() } + +// SupportCaseDecisionOutcome is the public outcome of a resolved case. +type SupportCaseDecisionOutcome string + +const ( + SupportCaseDecisionUpheld SupportCaseDecisionOutcome = "upheld" + SupportCaseDecisionPartiallyUpheld SupportCaseDecisionOutcome = "partially_upheld" + SupportCaseDecisionNotUpheld SupportCaseDecisionOutcome = "not_upheld" + SupportCaseDecisionAnswered SupportCaseDecisionOutcome = "answered" + SupportCaseDecisionAssessed SupportCaseDecisionOutcome = "assessed" +) + +func (outcome SupportCaseDecisionOutcome) IsKnown() bool { + switch outcome { + case SupportCaseDecisionUpheld, SupportCaseDecisionPartiallyUpheld, + SupportCaseDecisionNotUpheld, SupportCaseDecisionAnswered, SupportCaseDecisionAssessed: + return true + default: + return false + } +} + +// SupportCaseDecisionSnapshot is the public decision data persisted with a +// resolved case. It has no staff identity or internal note. +type SupportCaseDecisionSnapshot struct { + Outcome SupportCaseDecisionOutcome `json:"outcome"` + Reason string `json:"reason"` + DecidedAt time.Time `json:"decided_at"` +} + +func (SupportCaseDecisionSnapshot) String() string { return redactedSupportCaseDecision } +func (SupportCaseDecisionSnapshot) GoString() string { return redactedSupportCaseDecision } +func (SupportCaseDecisionSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCaseDecision) +} +func (snapshot SupportCaseDecisionSnapshot) LogValue() slog.Value { + return slog.StringValue(string(snapshot.Outcome)) +} + +// SupportCaseDecision is an immutable public decision. +type SupportCaseDecision struct { + snapshot SupportCaseDecisionSnapshot +} + +func NewSupportCaseDecision(snapshot SupportCaseDecisionSnapshot) (SupportCaseDecision, error) { + const location = "domain.NewSupportCaseDecision" + snapshot.DecidedAt = canonicalSupportTime(snapshot.DecidedAt) + if !snapshot.Outcome.IsKnown() || !validSupportCaseText(snapshot.Reason, maxSupportCasePublicTextRunes) || snapshot.DecidedAt.IsZero() { + return SupportCaseDecision{}, invalidSupportCase(location, "outcome, public reason, or decision time is invalid") + } + return SupportCaseDecision{snapshot: snapshot}, nil +} + +func (decision SupportCaseDecision) Outcome() SupportCaseDecisionOutcome { + return decision.snapshot.Outcome +} +func (decision SupportCaseDecision) Reason() string { return decision.snapshot.Reason } +func (decision SupportCaseDecision) DecidedAt() time.Time { return decision.snapshot.DecidedAt } +func (decision SupportCaseDecision) Snapshot() SupportCaseDecisionSnapshot { return decision.snapshot } +func (decision SupportCaseDecision) IsZero() bool { return decision.snapshot.DecidedAt.IsZero() } + +func (SupportCaseDecision) String() string { return redactedSupportCaseDecision } +func (SupportCaseDecision) GoString() string { return redactedSupportCaseDecision } +func (SupportCaseDecision) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCaseDecision) +} +func (decision SupportCaseDecision) LogValue() slog.Value { + return slog.StringValue(string(decision.snapshot.Outcome)) +} + +// SupportCaseEventKind identifies one public history event. +type SupportCaseEventKind string + +const ( + SupportCaseEventCreated SupportCaseEventKind = "created" + SupportCaseEventStatusChanged SupportCaseEventKind = "status_changed" + SupportCaseEventReply SupportCaseEventKind = "reply" + SupportCaseEventDecision SupportCaseEventKind = "decision" +) + +func (kind SupportCaseEventKind) IsKnown() bool { + switch kind { + case SupportCaseEventCreated, SupportCaseEventStatusChanged, SupportCaseEventReply, SupportCaseEventDecision: + return true + default: + return false + } +} + +// SupportCaseActorKind names only the kind of actor, never the staff member. +type SupportCaseActorKind string + +const ( + SupportCaseActorUser SupportCaseActorKind = "user" + SupportCaseActorSupport SupportCaseActorKind = "support" + SupportCaseActorSystem SupportCaseActorKind = "system" +) + +func (actor SupportCaseActorKind) IsKnown() bool { + return actor == SupportCaseActorUser || actor == SupportCaseActorSupport || actor == SupportCaseActorSystem +} + +// SupportCaseEventSnapshot is the public, immutable form of one history event. +type SupportCaseEventSnapshot struct { + Sequence int32 `json:"sequence"` + Kind SupportCaseEventKind `json:"kind"` + Actor SupportCaseActorKind `json:"actor"` + OccurredAt time.Time `json:"occurred_at"` + Status *SupportCaseStatus `json:"status,omitempty"` + Message *string `json:"message,omitempty"` +} + +func (SupportCaseEventSnapshot) String() string { return redactedSupportCaseEvent } +func (SupportCaseEventSnapshot) GoString() string { return redactedSupportCaseEvent } +func (SupportCaseEventSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCaseEvent) +} +func (event SupportCaseEventSnapshot) LogValue() slog.Value { + return slog.GroupValue( + slog.Int("sequence", int(event.Sequence)), + slog.String("kind", string(event.Kind)), + slog.String("actor", string(event.Actor)), + ) +} + +// SupportCaseEvent is one public event. It deliberately has no actor ID, +// assignment, evidence, or internal-note field. +type SupportCaseEvent struct { + snapshot SupportCaseEventSnapshot +} + +func RestoreSupportCaseEvent(snapshot SupportCaseEventSnapshot) (SupportCaseEvent, error) { + const location = "domain.RestoreSupportCaseEvent" + snapshot = cloneSupportCaseEventSnapshot(snapshot) + if err := validateSupportCaseEvent(location, snapshot); err != nil { + return SupportCaseEvent{}, err + } + return SupportCaseEvent{snapshot: cloneSupportCaseEventSnapshot(snapshot)}, nil +} + +func (event SupportCaseEvent) Snapshot() SupportCaseEventSnapshot { + return cloneSupportCaseEventSnapshot(event.snapshot) +} + +func (event SupportCaseEvent) String() string { return redactedSupportCaseEvent } +func (event SupportCaseEvent) GoString() string { return redactedSupportCaseEvent } +func (event SupportCaseEvent) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCaseEvent) +} +func (event SupportCaseEvent) LogValue() slog.Value { + return slog.GroupValue( + slog.Int("sequence", int(event.snapshot.Sequence)), + slog.String("kind", string(event.snapshot.Kind)), + slog.String("actor", string(event.snapshot.Actor)), + ) +} + +// SupportCaseSnapshot is the persistence projection of one private case. Its +// description and public messages may contain personal data and are redacted +// by its formatting and logging methods. +type SupportCaseSnapshot struct { + ID SupportCaseID `json:"id"` + Number SupportCaseNumber `json:"number"` + OwnerID uuid.UUID `json:"owner_id"` + Type SupportCaseType `json:"type"` + Status SupportCaseStatus `json:"status"` + Description string `json:"description"` + Object *SupportCaseReference `json:"object,omitempty"` + AssessmentTarget *SupportCaseAssessmentTarget `json:"assessment_target,omitempty"` + ComplaintReason *SupportCaseComplaintReason `json:"complaint_reason,omitempty"` + RubricVersion *int32 `json:"rubric_version,omitempty"` + RubricOpeningID *uuid.UUID `json:"rubric_opening_id,omitempty"` + RubricPolicyID *PolicyVersionID `json:"rubric_policy_version_id,omitempty"` + ResponseTarget SupportResponseTargetSnapshot `json:"response_target"` + Decision *SupportCaseDecisionSnapshot `json:"decision,omitempty"` + History []SupportCaseEventSnapshot `json:"history"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (SupportCaseSnapshot) String() string { return redactedSupportCase } +func (SupportCaseSnapshot) GoString() string { return redactedSupportCase } +func (SupportCaseSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCase) +} +func (snapshot SupportCaseSnapshot) LogValue() slog.Value { + return slog.GroupValue( + slog.String("case_id", snapshot.ID.String()), + slog.String("number", snapshot.Number.String()), + slog.String("type", string(snapshot.Type)), + slog.String("status", string(snapshot.Status)), + ) +} + +// NewSupportCaseInput is the user-stated content and server-resolved context +// for one new case. OwnerID is taken from the authenticated session. Object +// content, status, decision, and staff identity are not accepted here. +type NewSupportCaseInput struct { + Number SupportCaseNumber + OwnerID uuid.UUID + Type SupportCaseType + Description string + Object *SupportCaseReference + AssessmentTarget *SupportCaseAssessmentTarget + ComplaintReason *SupportCaseComplaintReason + RubricVersion *int32 + RubricOpeningID *uuid.UUID + RubricPolicyID *PolicyVersionID + ResponseTarget SupportResponseTarget + CreatedAt time.Time +} + +func (NewSupportCaseInput) String() string { return redactedSupportCase } +func (NewSupportCaseInput) GoString() string { return redactedSupportCase } +func (NewSupportCaseInput) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCase) +} +func (NewSupportCaseInput) LogValue() slog.Value { return slog.StringValue(redactedSupportCase) } + +// SupportCase is one account-owned case with immutable public creation +// history. Later status and decision commands will restore a new snapshot. +type SupportCase struct { + snapshot SupportCaseSnapshot +} + +// NewSupportCase assigns a case ID and creates the initial public event(s). +// Appeals and manual requests enter waiting_expert in the same creation +// history; no grade, attempt, or consent is created as a side effect. +func NewSupportCase(input NewSupportCaseInput) (SupportCase, error) { + const location = "domain.NewSupportCase" + if err := ValidateSupportCaseRequest(input); err != nil { + return SupportCase{}, fmt.Errorf("%s - validate request: %w", location, err) + } + if input.CreatedAt.IsZero() { + return SupportCase{}, invalidSupportCase(location, "creation time must be set") + } + id, err := NewSupportCaseID() + if err != nil { + return SupportCase{}, fmt.Errorf("%s - assign ID: %w", location, err) + } + createdAt := canonicalSupportTime(input.CreatedAt) + created := SupportCaseEventSnapshot{ + Sequence: 1, Kind: SupportCaseEventCreated, Actor: SupportCaseActorUser, + OccurredAt: createdAt, Status: supportCaseStatusPointer(SupportCaseStatusSubmitted), + } + history := []SupportCaseEventSnapshot{created} + status := SupportCaseStatusSubmitted + if input.Type.routesToExpert() { + status = SupportCaseStatusWaitingExpert + history = append(history, SupportCaseEventSnapshot{ + Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSystem, + OccurredAt: createdAt, Status: supportCaseStatusPointer(status), + }) + } + snapshot := SupportCaseSnapshot{ + ID: id, Number: input.Number, OwnerID: input.OwnerID, Type: input.Type, Status: status, + Description: input.Description, Object: input.Object, AssessmentTarget: input.AssessmentTarget, + ComplaintReason: input.ComplaintReason, RubricVersion: input.RubricVersion, + RubricOpeningID: input.RubricOpeningID, RubricPolicyID: input.RubricPolicyID, + ResponseTarget: input.ResponseTarget.Snapshot(), History: history, + CreatedAt: createdAt, UpdatedAt: createdAt, + } + return RestoreSupportCase(snapshot) +} + +// ValidateSupportCaseRequest checks client-supplied fields before resolving +// referenced objects. Ownership and object state remain use-case concerns. +func ValidateSupportCaseRequest(input NewSupportCaseInput) error { + const location = "domain.ValidateSupportCaseRequest" + if !input.Type.IsKnown() { + return &SupportCaseFieldError{Pointer: "/type", Reason: "is not supported"} + } + if !validSupportCaseDescription(input.Description) { + return &SupportCaseFieldError{Pointer: "/description", Reason: "must contain non-whitespace text"} + } + if err := validateSupportCaseRequestObject(input); err != nil { + return err + } + if err := validateSupportCaseRequestAssessmentTarget(input.AssessmentTarget); err != nil { + return err + } + if err := validateSupportCaseRequestComplaint(input.Type, input.Object, input.ComplaintReason); err != nil { + return err + } + snapshot := SupportCaseSnapshot{ + Type: input.Type, Description: input.Description, Object: input.Object, + AssessmentTarget: input.AssessmentTarget, ComplaintReason: input.ComplaintReason, + RubricVersion: input.RubricVersion, RubricOpeningID: input.RubricOpeningID, + RubricPolicyID: input.RubricPolicyID, + } + if err := validateSupportCaseFields(snapshot); err != nil { + return fmt.Errorf("%s - validate fields: %w", location, err) + } + return nil +} + +func validateSupportCaseRequestObject(input NewSupportCaseInput) error { + if input.Object == nil { + return nil + } + switch { + case !input.Object.Type.IsKnown(): + return &SupportCaseFieldError{Pointer: "/object/type", Reason: "is not supported"} + case input.Object.ID == uuid.Nil: + return &SupportCaseFieldError{Pointer: "/object/id", Reason: "must be set"} + case !supportObjectAllowed(input.Type, input.Object.Type): + return &SupportCaseFieldError{Pointer: "/object/type", Reason: "does not apply to this case type"} + default: + return nil + } +} + +func validateSupportCaseRequestAssessmentTarget(target *SupportCaseAssessmentTarget) error { + if target == nil { + return nil + } + if !target.Specialization.IsKnown() { + return &SupportCaseFieldError{Pointer: "/assessment_target/specialization", Reason: "is not supported"} + } + if !target.Grade.IsKnown() { + return &SupportCaseFieldError{Pointer: "/assessment_target/grade", Reason: "is not supported"} + } + return nil +} + +func validateSupportCaseRequestComplaint( + caseType SupportCaseType, + object *SupportCaseReference, + reason *SupportCaseComplaintReason, +) error { + if reason != nil && !reason.IsKnown() { + return &SupportCaseFieldError{Pointer: "/complaint_reason", Reason: "is not supported"} + } + if caseType == SupportCaseTypeComplaint && requiresInvitation(reason) && + (object == nil || object.Type != SupportCaseObjectInvitation) { + return &SupportCaseFieldError{Pointer: "/object/type", Reason: "must be invitation for this complaint reason"} + } + return nil +} + +// RestoreSupportCase validates a case read from storage before exposing it to +// an owner. A case remains readable by its owner even when its referenced +// object later changes state or access. +func RestoreSupportCase(snapshot SupportCaseSnapshot) (SupportCase, error) { + const location = "domain.RestoreSupportCase" + snapshot = cloneSupportCaseSnapshot(snapshot) + if err := validateSupportCaseSnapshot(location, snapshot); err != nil { + return SupportCase{}, err + } + return SupportCase{snapshot: cloneSupportCaseSnapshot(snapshot)}, nil +} + +func (supportCase SupportCase) Snapshot() SupportCaseSnapshot { + return cloneSupportCaseSnapshot(supportCase.snapshot) +} + +func (supportCase SupportCase) ID() SupportCaseID { return supportCase.snapshot.ID } +func (supportCase SupportCase) Number() SupportCaseNumber { return supportCase.snapshot.Number } +func (supportCase SupportCase) OwnerID() uuid.UUID { return supportCase.snapshot.OwnerID } +func (supportCase SupportCase) Type() SupportCaseType { return supportCase.snapshot.Type } +func (supportCase SupportCase) Status() SupportCaseStatus { return supportCase.snapshot.Status } +func (supportCase SupportCase) Description() string { return supportCase.snapshot.Description } +func (supportCase SupportCase) CreatedAt() time.Time { return supportCase.snapshot.CreatedAt } +func (supportCase SupportCase) UpdatedAt() time.Time { return supportCase.snapshot.UpdatedAt } +func (supportCase SupportCase) IsZero() bool { return supportCase.snapshot.ID.IsZero() } +func (supportCase SupportCase) ResponseTarget() SupportResponseTarget { + target, _ := NewSupportResponseTarget(supportCase.snapshot.ResponseTarget) + return target +} + +func (supportCase SupportCase) Object() *SupportCaseReference { + return cloneSupportCaseReference(supportCase.snapshot.Object) +} + +func (supportCase SupportCase) AssessmentTarget() *SupportCaseAssessmentTarget { + return cloneSupportCaseAssessmentTarget(supportCase.snapshot.AssessmentTarget) +} + +func (supportCase SupportCase) ComplaintReason() *SupportCaseComplaintReason { + return cloneComplaintReason(supportCase.snapshot.ComplaintReason) +} + +func (supportCase SupportCase) RubricVersion() *int32 { + return cloneInt32Pointer(supportCase.snapshot.RubricVersion) +} + +func (supportCase SupportCase) Decision() *SupportCaseDecision { + if supportCase.snapshot.Decision == nil { + return nil + } + decision, err := NewSupportCaseDecision(*supportCase.snapshot.Decision) + if err != nil { + return nil + } + return &decision +} + +func (supportCase SupportCase) History() []SupportCaseEvent { + events := make([]SupportCaseEvent, len(supportCase.snapshot.History)) + for index, snapshot := range supportCase.snapshot.History { + events[index] = SupportCaseEvent{snapshot: cloneSupportCaseEventSnapshot(snapshot)} + } + return events +} + +// Summary returns the list projection, which omits the description and event +// history so a list query need not load either field. +func (supportCase SupportCase) Summary() SupportCaseSummary { + var decisionOutcome *SupportCaseDecisionOutcome + if supportCase.snapshot.Decision != nil { + decisionOutcome = supportCaseDecisionOutcomePointer(supportCase.snapshot.Decision.Outcome) + } + return SupportCaseSummary{ + ID: supportCase.snapshot.ID, Number: supportCase.snapshot.Number, Type: supportCase.snapshot.Type, + Status: supportCase.snapshot.Status, Object: cloneSupportCaseReference(supportCase.snapshot.Object), + AssessmentTarget: cloneSupportCaseAssessmentTarget(supportCase.snapshot.AssessmentTarget), + ResponseTarget: cloneSupportResponseTargetSnapshot(supportCase.snapshot.ResponseTarget), + DecisionOutcome: decisionOutcome, CreatedAt: supportCase.snapshot.CreatedAt, UpdatedAt: supportCase.snapshot.UpdatedAt, + } +} + +func (SupportCase) String() string { return redactedSupportCase } +func (SupportCase) GoString() string { return redactedSupportCase } +func (SupportCase) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedSupportCase) +} +func (supportCase SupportCase) LogValue() slog.Value { return supportCase.snapshot.LogValue() } + +// SupportCaseSummary is a list item without description or event history. +type SupportCaseSummary struct { + ID SupportCaseID + Number SupportCaseNumber + Type SupportCaseType + Status SupportCaseStatus + Object *SupportCaseReference + AssessmentTarget *SupportCaseAssessmentTarget + ResponseTarget SupportResponseTargetSnapshot + DecisionOutcome *SupportCaseDecisionOutcome + CreatedAt time.Time + UpdatedAt time.Time +} + +// RestoreSupportCaseSummary validates the projection returned by the +// owner-scoped list query. It cannot validate private fields omitted from the +// query, so checks stay limited to the public summary contract. +func RestoreSupportCaseSummary(summary SupportCaseSummary) (SupportCaseSummary, error) { + const location = "domain.RestoreSupportCaseSummary" + summary = cloneSupportCaseSummary(summary) + if !validSupportCaseSummaryIdentity(summary) { + return SupportCaseSummary{}, invalidSupportCase(location, "identity, status, or timestamps are invalid") + } + if !validSupportCaseSummaryObject(summary) { + return SupportCaseSummary{}, invalidSupportCase(location, "object reference is invalid") + } + if !validSupportCaseSummaryAssessmentTarget(summary) { + return SupportCaseSummary{}, invalidSupportCase(location, "assessment target is invalid") + } + if err := validateSupportCaseSummaryFields(summary); err != nil { + return SupportCaseSummary{}, err + } + if !validSupportCaseSummaryResponseTarget(summary) { + return SupportCaseSummary{}, invalidSupportCase(location, "response target is invalid") + } + if err := validateSupportCaseSummaryDecision(summary); err != nil { + return SupportCaseSummary{}, err + } + return summary, nil +} + +func validSupportCaseSummaryIdentity(summary SupportCaseSummary) bool { + return !summary.ID.IsZero() && summary.Number.validFor(summary.CreatedAt) && summary.Type.IsKnown() && + summary.Status.IsKnown() && !summary.CreatedAt.IsZero() && !summary.UpdatedAt.Before(summary.CreatedAt) +} + +func validSupportCaseSummaryObject(summary SupportCaseSummary) bool { + if summary.Object == nil { + return true + } + return summary.Object.Type.IsKnown() && summary.Object.ID != uuid.Nil && + supportObjectAllowed(summary.Type, summary.Object.Type) +} + +func validSupportCaseSummaryAssessmentTarget(summary SupportCaseSummary) bool { + if summary.AssessmentTarget == nil { + return true + } + return summary.AssessmentTarget.Specialization.IsKnown() && summary.AssessmentTarget.Grade.IsKnown() +} + +func validateSupportCaseSummaryFields(summary SupportCaseSummary) error { + const location = "domain.RestoreSupportCaseSummary" + switch summary.Type { + case SupportCaseTypeSupport: + if summary.AssessmentTarget != nil { + return invalidSupportCase(location, "support summary has an assessment target") + } + case SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal: + if summary.Object == nil || summary.AssessmentTarget != nil { + return invalidSupportCase(location, "summary requires its matching object reference") + } + case SupportCaseTypeManualAssessment: + if summary.AssessmentTarget == nil || summary.Object != nil && summary.Object.Type != SupportCaseObjectAssessmentAttempt { + return invalidSupportCase(location, "manual assessment summary fields are invalid") + } + } + return nil +} + +func validSupportCaseSummaryResponseTarget(summary SupportCaseSummary) bool { + _, err := NewSupportResponseTarget(summary.ResponseTarget) + return err == nil && !summary.ResponseTarget.DueAt.Before(summary.CreatedAt) +} + +func validateSupportCaseSummaryDecision(summary SupportCaseSummary) error { + const location = "domain.RestoreSupportCaseSummary" + if (summary.Status == SupportCaseStatusResolved) != (summary.DecisionOutcome != nil) { + return invalidSupportCase(location, "decision summary does not match status") + } + if summary.DecisionOutcome == nil { + return nil + } + if !summary.DecisionOutcome.IsKnown() || !supportDecisionAllowed(summary.Type, *summary.DecisionOutcome) { + return invalidSupportCase(location, "decision outcome does not apply to the case type") + } + return nil +} + +func (SupportCaseSummary) String() string { return "[support case summary]" } +func (SupportCaseSummary) GoString() string { return "[support case summary]" } +func (SupportCaseSummary) Format(state fmt.State, _ rune) { + writeRedacted(state, "[support case summary]") +} + +// SupportCaseCreateOutcomeKind is the small set of responses retained for an +// idempotent create. Failure outcomes carry no object or reference details. +type SupportCaseCreateOutcomeKind string + +const ( + SupportCaseCreateOutcomeCreated SupportCaseCreateOutcomeKind = "created" + SupportCaseCreateOutcomeNotFound SupportCaseCreateOutcomeKind = "not_found" + SupportCaseCreateOutcomeStateConflict SupportCaseCreateOutcomeKind = "state_conflict" +) + +// SupportCaseCreateOutcomeSnapshot is the immutable result replayed for a +// live idempotency scope. It never stores a foreign object identifier in a +// not_found outcome. +type SupportCaseCreateOutcomeSnapshot struct { + Kind SupportCaseCreateOutcomeKind `json:"kind"` + Case *SupportCaseSnapshot `json:"case,omitempty"` + TargetWasLate bool `json:"target_was_late"` +} + +// SupportCaseCreateOutcome is the typed result persisted with a create key. +type SupportCaseCreateOutcome struct { + snapshot SupportCaseCreateOutcomeSnapshot +} + +func NewSupportCaseCreatedOutcome(supportCase SupportCase) (SupportCaseCreateOutcome, error) { + if supportCase.IsZero() { + return SupportCaseCreateOutcome{}, invalidSupportCase("domain.NewSupportCaseCreatedOutcome", "case must be set") + } + snapshot := supportCase.Snapshot() + if !isInitialSupportCaseSnapshot(snapshot) { + return SupportCaseCreateOutcome{}, invalidSupportCase("domain.NewSupportCaseCreatedOutcome", "case must be its original creation snapshot") + } + return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{ + Kind: SupportCaseCreateOutcomeCreated, Case: &snapshot, + TargetWasLate: supportCase.ResponseTarget().IsLate(supportCase.CreatedAt()), + }}, nil +} + +func isInitialSupportCaseSnapshot(snapshot SupportCaseSnapshot) bool { + initialStatus := SupportCaseStatusSubmitted + initialEvents := 1 + if snapshot.Type.routesToExpert() { + initialStatus = SupportCaseStatusWaitingExpert + initialEvents = 2 + } + return snapshot.Status == initialStatus && snapshot.CreatedAt.Equal(snapshot.UpdatedAt) && + len(snapshot.History) == initialEvents && snapshot.Decision == nil && snapshot.ResponseTarget.AnsweredAt == nil +} + +func NewSupportCaseNotFoundOutcome() SupportCaseCreateOutcome { + return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeNotFound}} +} + +func NewSupportCaseStateConflictOutcome() SupportCaseCreateOutcome { + return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeStateConflict}} +} + +func RestoreSupportCaseCreateOutcome(snapshot SupportCaseCreateOutcomeSnapshot) (SupportCaseCreateOutcome, error) { + const location = "domain.RestoreSupportCaseCreateOutcome" + switch snapshot.Kind { + case SupportCaseCreateOutcomeCreated: + if snapshot.Case == nil { + return SupportCaseCreateOutcome{}, invalidSupportCase(location, "created outcome requires its original case snapshot") + } + if _, err := RestoreSupportCase(*snapshot.Case); err != nil { + return SupportCaseCreateOutcome{}, fmt.Errorf("%s - restore original case: %w", location, err) + } + case SupportCaseCreateOutcomeNotFound, SupportCaseCreateOutcomeStateConflict: + if snapshot.Case != nil || snapshot.TargetWasLate { + return SupportCaseCreateOutcome{}, invalidSupportCase(location, "failure outcome cannot contain a case snapshot") + } + default: + return SupportCaseCreateOutcome{}, invalidSupportCase(location, "outcome kind is unknown") + } + return SupportCaseCreateOutcome{snapshot: cloneSupportCaseCreateOutcomeSnapshot(snapshot)}, nil +} + +func (outcome SupportCaseCreateOutcome) Kind() SupportCaseCreateOutcomeKind { + return outcome.snapshot.Kind +} + +func (outcome SupportCaseCreateOutcome) Case() (SupportCase, bool) { + if outcome.snapshot.Kind != SupportCaseCreateOutcomeCreated || outcome.snapshot.Case == nil { + return SupportCase{}, false + } + supportCase, err := RestoreSupportCase(*outcome.snapshot.Case) + if err != nil { + return SupportCase{}, false + } + return supportCase, true +} + +// CreationTargetWasLate reports the target's state at the instant the case +// was created. A 201 replay must use this stored value, while a current GET +// evaluates ResponseTarget().IsLate(now). +func (outcome SupportCaseCreateOutcome) CreationTargetWasLate() (bool, bool) { + if outcome.snapshot.Kind != SupportCaseCreateOutcomeCreated || outcome.snapshot.Case == nil { + return false, false + } + return outcome.snapshot.TargetWasLate, true +} + +func (outcome SupportCaseCreateOutcome) Snapshot() SupportCaseCreateOutcomeSnapshot { + return cloneSupportCaseCreateOutcomeSnapshot(outcome.snapshot) +} + +func (outcome SupportCaseCreateOutcome) IsZero() bool { return outcome.snapshot.Kind == "" } +func (SupportCaseCreateOutcome) String() string { return "[support case create outcome]" } +func (SupportCaseCreateOutcome) GoString() string { return "[support case create outcome]" } +func (SupportCaseCreateOutcome) Format(state fmt.State, _ rune) { + writeRedacted(state, "[support case create outcome]") +} +func (outcome SupportCaseCreateOutcome) LogValue() slog.Value { + return slog.StringValue(string(outcome.snapshot.Kind)) +} + +func validateSupportCaseSnapshot(location string, snapshot SupportCaseSnapshot) error { + if err := validateSupportCaseIdentityAndContent(location, snapshot); err != nil { + return err + } + if err := validateSupportCaseFields(snapshot); err != nil { + return fmt.Errorf("%s - validate case fields: %w", location, err) + } + if err := validateSupportCaseTarget(location, snapshot); err != nil { + return err + } + if err := validateSupportCaseHistory(location, snapshot); err != nil { + return err + } + if err := validateSupportCaseDecision(location, snapshot); err != nil { + return err + } + return nil +} + +func validateSupportCaseIdentityAndContent(location string, snapshot SupportCaseSnapshot) error { + if snapshot.ID.IsZero() || snapshot.OwnerID == uuid.Nil { + return invalidSupportCase(location, "case and owner identifiers must be set") + } + if !snapshot.Number.validFor(snapshot.CreatedAt) { + return invalidSupportCase(location, "number must match the UTC creation year") + } + if !snapshot.Type.IsKnown() || !snapshot.Status.IsKnown() { + return invalidSupportCase(location, "case type or status is unknown") + } + if !validSupportCaseDescription(snapshot.Description) { + return invalidSupportCase(location, "description must be valid, non-blank text of at most 4000 characters") + } + if snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt) { + return invalidSupportCase(location, "creation and update times are invalid") + } + if len(snapshot.History) == 0 || len(snapshot.History) > maxSupportCaseEvents || + !snapshot.Status.IsTerminal() && len(snapshot.History) >= maxSupportCaseEvents { + return invalidSupportCase(location, "public history must leave room for a terminal event and contain at most 200 events") + } + return nil +} + +func validateSupportCaseTarget(location string, snapshot SupportCaseSnapshot) error { + target, err := NewSupportResponseTarget(snapshot.ResponseTarget) + if err != nil { + return fmt.Errorf("%s - validate response target: %w", location, err) + } + if target.DueAt().Before(snapshot.CreatedAt) { + return invalidSupportCase(location, "response target cannot precede creation") + } + if answeredAt := target.AnsweredAt(); answeredAt != nil && answeredAt.Before(snapshot.CreatedAt) { + return invalidSupportCase(location, "answer time cannot precede creation") + } + return nil +} + +func validateSupportCaseDecision(location string, snapshot SupportCaseSnapshot) error { + if snapshot.Decision != nil { + decision, err := NewSupportCaseDecision(*snapshot.Decision) + if err != nil { + return fmt.Errorf("%s - validate decision: %w", location, err) + } + if !supportDecisionAllowed(snapshot.Type, decision.Outcome()) { + return invalidSupportCase(location, "decision outcome does not apply to this case type") + } + } + switch snapshot.Status { + case SupportCaseStatusResolved: + return validateResolvedSupportCaseDecision(location, snapshot) + case SupportCaseStatusClosed: + if snapshot.Decision != nil { + return invalidSupportCase(location, "only a resolved case may contain a decision") + } + return validateClosedSupportCase(location, snapshot) + case SupportCaseStatusSubmitted, SupportCaseStatusInReview, + SupportCaseStatusWaitingForUser, SupportCaseStatusWaitingExpert: + if snapshot.Decision != nil { + return invalidSupportCase(location, "only a resolved case may contain a decision") + } + } + return nil +} + +func validateResolvedSupportCaseDecision(location string, snapshot SupportCaseSnapshot) error { + if snapshot.Decision == nil { + return invalidSupportCase(location, "a resolved case requires a public decision") + } + last := snapshot.History[len(snapshot.History)-1] + if last.Kind != SupportCaseEventDecision || last.Message == nil || + *last.Message != snapshot.Decision.Reason || !last.OccurredAt.Equal(snapshot.Decision.DecidedAt) { + return invalidSupportCase(location, "resolved case must end with its public decision event") + } + return nil +} + +func validateClosedSupportCase(location string, snapshot SupportCaseSnapshot) error { + last := snapshot.History[len(snapshot.History)-1] + if last.Kind != SupportCaseEventStatusChanged || last.Status == nil || + *last.Status != SupportCaseStatusClosed || last.Message == nil { + return invalidSupportCase(location, "closed case must end with a public closure reason") + } + return nil +} + +func validateSupportCaseFields(snapshot SupportCaseSnapshot) error { + if err := validateSupportCaseObject(snapshot); err != nil { + return err + } + if err := validateSupportCaseMetadata(snapshot); err != nil { + return err + } + return validateSupportCaseTypeFields(snapshot) +} + +func validateSupportCaseObject(snapshot SupportCaseSnapshot) error { + if snapshot.Object == nil { + return nil + } + if !snapshot.Object.Type.IsKnown() || snapshot.Object.ID == uuid.Nil || !supportObjectAllowed(snapshot.Type, snapshot.Object.Type) { + return invalidSupportCase("domain.RestoreSupportCase", "object type or identifier is not allowed") + } + return nil +} + +func validateSupportCaseMetadata(snapshot SupportCaseSnapshot) error { + if snapshot.AssessmentTarget != nil && (!snapshot.AssessmentTarget.Specialization.IsKnown() || !snapshot.AssessmentTarget.Grade.IsKnown()) { + return invalidSupportCase("domain.RestoreSupportCase", "assessment target is not in the MVP catalog") + } + if snapshot.ComplaintReason != nil && !snapshot.ComplaintReason.IsKnown() { + return invalidSupportCase("domain.RestoreSupportCase", "complaint reason is unknown") + } + if snapshot.RubricVersion != nil && *snapshot.RubricVersion < 1 { + return invalidSupportCase("domain.RestoreSupportCase", "rubric version must be positive when present") + } + if err := validateSupportCaseRubricPin(snapshot); err != nil { + return err + } + return nil +} + +func validateSupportCaseRubricPin(snapshot SupportCaseSnapshot) error { + hasVersion := snapshot.RubricVersion != nil + hasOpening := snapshot.RubricOpeningID != nil + hasPolicy := snapshot.RubricPolicyID != nil + if !hasVersion && !hasOpening && !hasPolicy { + return nil + } + if snapshot.Type != SupportCaseTypeManualAssessment || !hasVersion || !hasOpening || !hasPolicy || + *snapshot.RubricOpeningID == uuid.Nil || snapshot.RubricPolicyID.IsZero() { + return invalidSupportCase("domain.RestoreSupportCase", "rubric version and private policy pins must be complete for a manual assessment") + } + return nil +} + +func validateSupportCaseTypeFields(snapshot SupportCaseSnapshot) error { + switch snapshot.Type { + case SupportCaseTypeSupport: + return validateSupportFields(snapshot) + case SupportCaseTypeComplaint: + return validateComplaintFields(snapshot) + case SupportCaseTypeGradeAppeal: + return validateGradeAppealFields(snapshot) + case SupportCaseTypeAnticheatAppeal: + return validateAnticheatAppealFields(snapshot) + case SupportCaseTypeManualAssessment: + return validateManualAssessmentFields(snapshot) + } + return invalidSupportCase("domain.RestoreSupportCase", "case type is unknown") +} + +func validateSupportFields(snapshot SupportCaseSnapshot) error { + if snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil { + return invalidSupportCase("domain.RestoreSupportCase", "support case has fields from another case type") + } + return nil +} + +func validateComplaintFields(snapshot SupportCaseSnapshot) error { + if snapshot.Object == nil || snapshot.ComplaintReason == nil || snapshot.AssessmentTarget != nil || snapshot.RubricVersion != nil { + return invalidSupportCase("domain.RestoreSupportCase", "complaint requires an object and reason only") + } + if requiresInvitation(snapshot.ComplaintReason) && snapshot.Object.Type != SupportCaseObjectInvitation { + return invalidSupportCase("domain.RestoreSupportCase", "complaint reason requires an invitation reference") + } + return nil +} + +func validateGradeAppealFields(snapshot SupportCaseSnapshot) error { + if snapshot.Object == nil || snapshot.AssessmentTarget != nil || snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil { + return invalidSupportCase("domain.RestoreSupportCase", "grade appeal requires an allowed object only") + } + return nil +} + +func validateAnticheatAppealFields(snapshot SupportCaseSnapshot) error { + if snapshot.Object == nil || snapshot.AssessmentTarget != nil || snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil { + return invalidSupportCase("domain.RestoreSupportCase", "anti-cheat appeal requires an attempt only") + } + return nil +} + +func validateManualAssessmentFields(snapshot SupportCaseSnapshot) error { + if snapshot.AssessmentTarget == nil || snapshot.ComplaintReason != nil { + return invalidSupportCase("domain.RestoreSupportCase", "manual assessment requires a category and no complaint reason") + } + return nil +} + +func validateSupportCaseHistory(location string, snapshot SupportCaseSnapshot) error { + if err := validateSupportCaseEventOrder(location, snapshot); err != nil { + return err + } + if err := validateSupportCaseInitialHistory(location, snapshot); err != nil { + return err + } + currentStatus := supportCaseHistoryStatus(snapshot.History) + if currentStatus != snapshot.Status || !snapshot.UpdatedAt.Equal(snapshot.History[len(snapshot.History)-1].OccurredAt) { + return invalidSupportCase(location, "case state and latest history event do not match") + } + if err := validateSupportCaseResponseTargetAnswer(location, snapshot); err != nil { + return err + } + return nil +} + +func validateSupportCaseResponseTargetAnswer(location string, snapshot SupportCaseSnapshot) error { + target := snapshot.ResponseTarget + if target.CalendarVersion < 1 { + return invalidSupportCase(location, "response target calendar version must be positive") + } + if target.AnsweredAt != nil && target.AnsweredAt.After(snapshot.UpdatedAt) { + return invalidSupportCase(location, "response target answer cannot follow the case update time") + } + var firstAnswerAt *time.Time + for _, event := range snapshot.History { + if supportCaseEventMeetsTarget(snapshot.Type, event) { + occurredAt := event.OccurredAt + firstAnswerAt = &occurredAt + break + } + } + if (target.AnsweredAt == nil) != (firstAnswerAt == nil) { + return invalidSupportCase(location, "response target answer time must match the first qualifying public event") + } + if firstAnswerAt != nil && !target.AnsweredAt.Equal(*firstAnswerAt) { + return invalidSupportCase(location, "response target answer time must match the first qualifying public event") + } + return nil +} + +func supportCaseEventMeetsTarget(caseType SupportCaseType, event SupportCaseEventSnapshot) bool { + switch event.Kind { + case SupportCaseEventCreated: + return false + case SupportCaseEventDecision: + return true + case SupportCaseEventStatusChanged: + return event.Status != nil && *event.Status == SupportCaseStatusClosed + case SupportCaseEventReply: + return caseType == SupportCaseTypeSupport || caseType == SupportCaseTypeComplaint + } + return false +} + +func validateSupportCaseEventOrder(location string, snapshot SupportCaseSnapshot) error { + var previousAt time.Time + for index, eventSnapshot := range snapshot.History { + if err := validateSupportCaseEvent(location, eventSnapshot); err != nil { + return err + } + if eventSnapshot.Sequence != int32(index+1) || index > 0 && eventSnapshot.OccurredAt.Before(previousAt) { + return invalidSupportCase(location, "history sequence or time order is invalid") + } + if index > 0 && eventSnapshot.Kind == SupportCaseEventCreated { + return invalidSupportCase(location, "history cannot repeat the created event") + } + previousAt = eventSnapshot.OccurredAt + } + return nil +} + +func validateSupportCaseInitialHistory(location string, snapshot SupportCaseSnapshot) error { + created := snapshot.History[0] + if created.Kind != SupportCaseEventCreated || created.Actor != SupportCaseActorUser || + created.Status == nil || *created.Status != SupportCaseStatusSubmitted || + created.Message != nil || !created.OccurredAt.Equal(snapshot.CreatedAt) { + return invalidSupportCase(location, "history must begin with the author's created event") + } + if snapshot.Type.routesToExpert() { + return validateSupportCaseExpertRoutingEvent(location, snapshot.History) + } + return nil +} + +func validateSupportCaseExpertRoutingEvent(location string, history []SupportCaseEventSnapshot) error { + if len(history) < 2 { + return invalidSupportCase(location, "appeal and manual case history is missing its routing event") + } + event := history[1] + if event.Kind != SupportCaseEventStatusChanged || event.Actor != SupportCaseActorSystem || + event.Status == nil || *event.Status != SupportCaseStatusWaitingExpert || event.Message != nil { + return invalidSupportCase(location, "appeal and manual cases require an initial expert-routing event") + } + return nil +} + +func supportCaseHistoryStatus(history []SupportCaseEventSnapshot) SupportCaseStatus { + status := SupportCaseStatusSubmitted + for _, event := range history { + if event.Status != nil { + status = *event.Status + } + } + return status +} + +func validateSupportCaseEvent(location string, event SupportCaseEventSnapshot) error { + if event.Sequence < 1 || !event.Kind.IsKnown() || !event.Actor.IsKnown() || event.OccurredAt.IsZero() { + return invalidSupportCase(location, "event identity or time is invalid") + } + if event.Status != nil && !event.Status.IsKnown() { + return invalidSupportCase(location, "event status is unknown") + } + if event.Message != nil && !validSupportCaseText(*event.Message, maxSupportCasePublicTextRunes) { + return invalidSupportCase(location, "event message is invalid public text") + } + return validateSupportCaseEventShape(location, event) +} + +func validateSupportCaseEventShape(location string, event SupportCaseEventSnapshot) error { + switch event.Kind { + case SupportCaseEventCreated: + return validateSupportCaseCreatedEvent(location, event) + case SupportCaseEventStatusChanged: + return validateSupportCaseStatusEvent(location, event) + case SupportCaseEventReply: + return validateSupportCaseReplyEvent(location, event) + case SupportCaseEventDecision: + return validateSupportCaseDecisionEvent(location, event) + } + return invalidSupportCase(location, "event kind is unknown") +} + +func validateSupportCaseCreatedEvent(location string, event SupportCaseEventSnapshot) error { + if event.Actor != SupportCaseActorUser || event.Status == nil || *event.Status != SupportCaseStatusSubmitted || event.Message != nil { + return invalidSupportCase(location, "created event fields are invalid") + } + return nil +} + +func validateSupportCaseStatusEvent(location string, event SupportCaseEventSnapshot) error { + if event.Actor == SupportCaseActorUser || event.Status == nil { + return invalidSupportCase(location, "status event fields are invalid") + } + return nil +} + +func validateSupportCaseReplyEvent(location string, event SupportCaseEventSnapshot) error { + if event.Status != nil || event.Message == nil { + return invalidSupportCase(location, "reply event requires public text and no status") + } + return nil +} + +func validateSupportCaseDecisionEvent(location string, event SupportCaseEventSnapshot) error { + if event.Actor != SupportCaseActorSupport || event.Status == nil || *event.Status != SupportCaseStatusResolved || event.Message == nil { + return invalidSupportCase(location, "decision event fields are invalid") + } + return nil +} + +func supportObjectAllowed(caseType SupportCaseType, objectType SupportCaseObjectType) bool { + switch caseType { + case SupportCaseTypeSupport: + return objectType.IsKnown() + case SupportCaseTypeComplaint: + return objectType == SupportCaseObjectOrganization || objectType == SupportCaseObjectInvitation + case SupportCaseTypeGradeAppeal: + return objectType == SupportCaseObjectAssessmentAttempt || objectType == SupportCaseObjectSupportCase + case SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment: + return objectType == SupportCaseObjectAssessmentAttempt + default: + return false + } +} + +func supportDecisionAllowed(caseType SupportCaseType, outcome SupportCaseDecisionOutcome) bool { + switch caseType { + case SupportCaseTypeSupport: + return outcome == SupportCaseDecisionAnswered + case SupportCaseTypeManualAssessment: + return outcome == SupportCaseDecisionAssessed + case SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal: + return outcome == SupportCaseDecisionUpheld || outcome == SupportCaseDecisionPartiallyUpheld || + outcome == SupportCaseDecisionNotUpheld + default: + return false + } +} + +func requiresInvitation(reason *SupportCaseComplaintReason) bool { + return reason != nil && (*reason == SupportComplaintOfferContent || *reason == SupportComplaintSalaryTermsViolation) +} + +func validSupportCaseDescription(value string) bool { + if !utf8.ValidString(value) || strings.ContainsRune(value, 0) || utf8.RuneCountInString(value) < 1 || + utf8.RuneCountInString(value) > maxSupportCaseDescriptionRunes { + return false + } + return strings.ContainsFunc(value, func(character rune) bool { return !unicode.IsSpace(character) && character != '\uFEFF' }) +} + +func validSupportCaseText(value string, maximumRunes int) bool { + return utf8.ValidString(value) && !strings.ContainsRune(value, 0) && utf8.RuneCountInString(value) >= 1 && + utf8.RuneCountInString(value) <= maximumRunes +} + +func invalidSupportCase(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidSupportCase) +} + +func cloneSupportCaseSnapshot(snapshot SupportCaseSnapshot) SupportCaseSnapshot { + cloned := snapshot + cloned.CreatedAt = canonicalSupportTime(snapshot.CreatedAt) + cloned.UpdatedAt = canonicalSupportTime(snapshot.UpdatedAt) + cloned.Object = cloneSupportCaseReference(snapshot.Object) + cloned.AssessmentTarget = cloneSupportCaseAssessmentTarget(snapshot.AssessmentTarget) + cloned.ComplaintReason = cloneComplaintReason(snapshot.ComplaintReason) + cloned.RubricVersion = cloneInt32Pointer(snapshot.RubricVersion) + cloned.RubricOpeningID = cloneUUIDPointer(snapshot.RubricOpeningID) + cloned.RubricPolicyID = clonePolicyVersionIDPointer(snapshot.RubricPolicyID) + cloned.ResponseTarget = cloneSupportResponseTargetSnapshot(snapshot.ResponseTarget) + if snapshot.Decision != nil { + decision := *snapshot.Decision + decision.DecidedAt = canonicalSupportTime(decision.DecidedAt) + cloned.Decision = &decision + } + cloned.History = make([]SupportCaseEventSnapshot, len(snapshot.History)) + for index, event := range snapshot.History { + cloned.History[index] = cloneSupportCaseEventSnapshot(event) + } + return cloned +} + +func cloneSupportCaseSummary(summary SupportCaseSummary) SupportCaseSummary { + cloned := summary + cloned.Object = cloneSupportCaseReference(summary.Object) + cloned.AssessmentTarget = cloneSupportCaseAssessmentTarget(summary.AssessmentTarget) + cloned.ResponseTarget = cloneSupportResponseTargetSnapshot(summary.ResponseTarget) + if summary.DecisionOutcome != nil { + outcome := *summary.DecisionOutcome + cloned.DecisionOutcome = &outcome + } + return cloned +} + +func cloneSupportCaseEventSnapshot(snapshot SupportCaseEventSnapshot) SupportCaseEventSnapshot { + cloned := snapshot + cloned.OccurredAt = canonicalSupportTime(snapshot.OccurredAt) + if snapshot.Status != nil { + status := *snapshot.Status + cloned.Status = &status + } + if snapshot.Message != nil { + message := *snapshot.Message + cloned.Message = &message + } + return cloned +} + +func cloneSupportCaseCreateOutcomeSnapshot(snapshot SupportCaseCreateOutcomeSnapshot) SupportCaseCreateOutcomeSnapshot { + cloned := snapshot + if snapshot.Case != nil { + caseSnapshot := cloneSupportCaseSnapshot(*snapshot.Case) + cloned.Case = &caseSnapshot + } + return cloned +} + +func cloneSupportResponseTargetSnapshot(snapshot SupportResponseTargetSnapshot) SupportResponseTargetSnapshot { + cloned := snapshot + cloned.DueAt = canonicalSupportTime(snapshot.DueAt) + cloned.AnsweredAt = canonicalSupportTimePointer(snapshot.AnsweredAt) + return cloned +} + +func cloneSupportCaseReference(value *SupportCaseReference) *SupportCaseReference { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func cloneSupportCaseAssessmentTarget(value *SupportCaseAssessmentTarget) *SupportCaseAssessmentTarget { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func cloneComplaintReason(value *SupportCaseComplaintReason) *SupportCaseComplaintReason { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func supportCaseStatusPointer(value SupportCaseStatus) *SupportCaseStatus { return &value } + +func supportCaseDecisionOutcomePointer(value SupportCaseDecisionOutcome) *SupportCaseDecisionOutcome { + return &value +} + +func cloneInt32Pointer(value *int32) *int32 { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func cloneUUIDPointer(value *uuid.UUID) *uuid.UUID { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func clonePolicyVersionIDPointer(value *PolicyVersionID) *PolicyVersionID { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func cloneTimePointer(value *time.Time) *time.Time { + if value == nil { + return nil + } + cloned := canonicalSupportTime(*value) + return &cloned +} + +func canonicalSupportTime(value time.Time) time.Time { + return value.UTC().Truncate(time.Microsecond) +} + +func canonicalSupportTimePointer(value *time.Time) *time.Time { + if value == nil { + return nil + } + cloned := canonicalSupportTime(*value) + return &cloned +} diff --git a/backend/internal/domain/support_case_test.go b/backend/internal/domain/support_case_test.go new file mode 100644 index 0000000..5be11fc --- /dev/null +++ b/backend/internal/domain/support_case_test.go @@ -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 +} diff --git a/backend/internal/domain/support_policy.go b/backend/internal/domain/support_policy.go new file mode 100644 index 0000000..86780f3 --- /dev/null +++ b/backend/internal/domain/support_policy.go @@ -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 +} diff --git a/backend/internal/domain/support_policy_test.go b/backend/internal/domain/support_policy_test.go new file mode 100644 index 0000000..a754fb8 --- /dev/null +++ b/backend/internal/domain/support_policy_test.go @@ -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) + } +} diff --git a/backend/internal/domain/visibility.go b/backend/internal/domain/visibility.go index 4e64039..48a83a9 100644 --- a/backend/internal/domain/visibility.go +++ b/backend/internal/domain/visibility.go @@ -80,12 +80,15 @@ const MaxHiddenOrganizations = 1000 type CardField string const ( - CardFieldCategories CardField = "categories" - CardFieldStack CardField = "stack" - CardFieldExperience CardField = "experience" - CardFieldSoftSkills CardField = "soft_skills" - CardFieldLocation CardField = "location" - CardFieldRelocation CardField = "relocation" + CardFieldCategories CardField = "categories" + CardFieldStack CardField = "stack" + CardFieldExperience CardField = "experience" + CardFieldSoftSkills CardField = "soft_skills" + CardFieldLocation CardField = "location" + CardFieldRelocation CardField = "relocation" + CardFieldSelfAssessment CardField = "self_assessment" + CardFieldWorkFormats CardField = "work_formats" + CardFieldSalaryCompatibility CardField = "salary_compatibility" ) const ( @@ -99,6 +102,7 @@ const ( var cardFields = []CardField{ CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation, + CardFieldSelfAssessment, CardFieldWorkFormats, CardFieldSalaryCompatibility, } // CardFields returns every card field the contract defines. diff --git a/backend/internal/port/outbound/assessment_attempt.go b/backend/internal/port/outbound/assessment_attempt.go new file mode 100644 index 0000000..7fe0fb6 --- /dev/null +++ b/backend/internal/port/outbound/assessment_attempt.go @@ -0,0 +1,248 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrAssessmentAttemptNotFound covers both an unknown attempt and one + // owned by another candidate. + ErrAssessmentAttemptNotFound = errors.New("assessment attempt not found") + // ErrAssessmentAttemptConflict reports an active-attempt, quota, retry, or + // availability constraint that prevented attempt creation. + ErrAssessmentAttemptConflict = errors.New("assessment attempt conflicts with current state") + // ErrAssessmentAttemptIdempotencyConflict reports reuse of one idempotency + // key for a different canonical request body. + ErrAssessmentAttemptIdempotencyConflict = errors.New("assessment attempt idempotency key was reused") + // ErrAssessmentAttemptVersionConflict reports an attempt changed after the + // caller read it. + ErrAssessmentAttemptVersionConflict = errors.New("assessment attempt version changed") + // ErrAssessmentAttemptResultNotFound reports a completed attempt with no + // persisted immutable decision snapshot. + ErrAssessmentAttemptResultNotFound = errors.New("assessment attempt result not found") +) + +// AssessmentAttemptIdempotencyScope is the server HMAC of the operation, +// client key, and authenticated actor. Raw keys never reach the repository. +type AssessmentAttemptIdempotencyScope [IdempotencyDigestSize]byte + +// AssessmentAttemptRequestFingerprint is the server HMAC of the canonical +// request body. It cannot be used as an offline check of a submitted answer. +type AssessmentAttemptRequestFingerprint [IdempotencyDigestSize]byte + +// AssessmentAttemptCreateOutcome is the immutable public result retained for +// the idempotency window. A created response contains its typed allowlisted +// projection; a conflict contains only a stable problem code. +type AssessmentAttemptCreateOutcome struct { + StatusCode int16 + Response domain.AssessmentAttemptPublicSnapshot + ProblemCode string +} + +// AssessmentAttemptCreateResult marks whether the outcome came from the +// immutable idempotency snapshot rather than a new command execution. +type AssessmentAttemptCreateResult struct { + Outcome AssessmentAttemptCreateOutcome + Replayed bool +} + +// AssessmentAttemptSessionResult is the original HTTP 200 public projection +// for a session command, including an unchanged terminal attempt. +type AssessmentAttemptSessionResult struct { + Response domain.AssessmentAttemptPublicSnapshot + Replayed bool +} + +// AssessmentAttemptCommandOutcome is an immutable answer or finalize +// response retained for the idempotency window. +type AssessmentAttemptCommandOutcome struct { + StatusCode int16 + Response domain.AssessmentAttemptPublicSnapshot + ProblemCode string + PendingItemIDs []uuid.UUID +} + +// AssessmentAttemptCommandResult marks whether the outcome is a replay. +type AssessmentAttemptCommandResult struct { + Outcome AssessmentAttemptCommandOutcome + Replayed bool +} + +// AssessmentActiveAttemptSummary is the only active-attempt data needed by +// availability preflight. It intentionally excludes frozen task content. +type AssessmentActiveAttemptSummary struct { + ID domain.AssessmentAttemptID + ExpiresAt time.Time +} + +// AssessmentRootAvailabilitySummary contains lifecycle timestamps for one +// root and the latest attempt in its correction chain. It is a private +// candidate-scoped read model and contains no answers or task content. +type AssessmentRootAvailabilitySummary struct { + RootTargetGrade domain.GradeCode + RootCreatedAt time.Time + RootUpdatedAt time.Time + RootExpiresAt time.Time + RootState domain.AssessmentAttemptState + RootOutcome domain.AssessmentAttemptOutcome + RootChainDeadline time.Time + LatestTargetGrade domain.GradeCode + LatestUpdatedAt time.Time + LatestExpiresAt time.Time + LatestState domain.AssessmentAttemptState + LatestOutcome domain.AssessmentAttemptOutcome + LatestChainDeadline time.Time + LatestPlatformError string +} + +// AssessmentRootQuotaSnapshot is the current rolling-window count and the +// earliest instant a new root slot opens, if the quota is currently full. +type AssessmentRootQuotaSnapshot struct { + Count int32 + AvailableAt *time.Time +} + +// AssessmentAttemptRepositories exposes the repository bound to a UnitOfWork +// transaction. +type AssessmentAttemptRepositories interface { + AssessmentAttempts() AssessmentAttemptRepository +} + +// AssessmentAttemptRepository persists complete attempt snapshots, frozen +// item instances, and immutable idempotent outcomes. Implementations bind +// every method to the surrounding unit of work and preserve candidate +// ownership in their queries. +type AssessmentAttemptRepository interface { + // Create atomically inserts an attempt and its frozen items. The caller + // holds the actor+specialization transaction lock and stores the result + // snapshot before the unit of work commits. + Create(ctx context.Context, attempt domain.AssessmentAttempt) error + + // LockScope serializes creation and quota checks for one candidate and + // specialization. A nil specialization is the separate training scope. + LockScope(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode) error + + // GetActiveForSpecialization returns the one active real attempt, if any. + // The partial unique index remains the final concurrency guard. + GetActiveForSpecialization(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (domain.AssessmentAttempt, bool, error) + + // GetActiveTraining returns the one active training attempt, if any. + // Training remains outside real assessment quotas and categories. + GetActiveTraining(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttempt, bool, error) + + // GetLatestRootForSpecialization returns the newest root attempt, optionally + // restricted to one target grade, for retry and promotion intervals. + GetLatestRootForSpecialization( + ctx context.Context, + userID uuid.UUID, + specialization domain.SpecializationCode, + grade *domain.GradeCode, + ) (domain.AssessmentAttempt, bool, error) + + // CountRootAttemptsSince counts root attempts for the supplied candidate + // and optional specialization at or after since. Corrective and training + // attempts never consume root quota. + CountRootAttemptsSince(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode, since time.Time) (int32, error) + + // GetAvailabilityActiveAttempt reads the current real attempt without a + // row lock or lifecycle update. + GetAvailabilityActiveAttempt(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (AssessmentActiveAttemptSummary, bool, error) + + // ListAvailabilityRootSummaries returns recent eligible root attempts and + // their latest correction-chain headers without locking or loading items. + ListAvailabilityRootSummaries(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, since time.Time) ([]AssessmentRootAvailabilitySummary, error) + + // GetRootQuotaSnapshot returns a candidate-wide root quota view for one + // policy window. availableAt is nil unless a new root is currently blocked. + GetRootQuotaSnapshot(ctx context.Context, userID uuid.UUID, since, asOf time.Time, window time.Duration, maxAttempts int32) (AssessmentRootQuotaSnapshot, error) + + // ListDisclosedFamilyKeys returns families actually shown by root or + // corrective attempts since the non-repeat boundary; frozen future items + // are excluded. + ListDisclosedFamilyKeys(ctx context.Context, userID uuid.UUID, since time.Time) ([]domain.AssessmentFamilyKey, error) + + // ListCorrectionChain returns the root and all its corrections in creation + // order, with their frozen items, for domain eligibility validation. + ListCorrectionChain(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, rootID domain.AssessmentAttemptID) ([]domain.AssessmentAttempt, error) + + // SaveCreateOutcome records the original 201 or 409 response under the + // already-reserved idempotency scope. The generic IdempotencyRecord and + // this outcome commit in the same transaction and share its 24-hour expiry. + SaveCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCreateOutcome) error + + // DeleteExpiredOutcome replaces a typed outcome only after generic Reserve + // created a new idempotency window for the same scope. + DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error + + // GetCreateOutcome returns the immutable 201 or 409 response snapshot for a + // live key. Missing data for a live generic idempotency record is an + // integrity error, not a cache miss. + GetCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCreateOutcome, error) + + // GetForCandidate is owner-scoped. An unknown or foreign attempt returns + // ErrAssessmentAttemptNotFound and never changes session or attempt state. + GetForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) + + // GetKindForCandidate reads the immutable kind without acquiring an attempt + // row lock. Session commands use it before checking C3, then lock the row. + GetKindForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptKind, error) + + // GetForCandidateForUpdate obtains the owner-scoped write lock for a command. + // Callers must take any required consent lock before this row lock. + GetForCandidateForUpdate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) + + // StartOrResumeSession performs the version check and session transition + // atomically. It returns changed=false for an active-session repeat or a + // terminal attempt; a matching key's original 200 is stored separately. + StartOrResumeSession( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, + expectedVersion int64, + at time.Time, + ) (domain.AssessmentAttempt, bool, error) + + // SaveAnswer atomically makes one unanswered frozen item immutable and + // advances its owner-scoped attempt transition from current to next. + SaveAnswer(ctx context.Context, current, next domain.AssessmentAttempt, itemID uuid.UUID) error + + // SaveTransition atomically stores a non-answer lifecycle transition after + // a command has locked the attempt row. + SaveTransition(ctx context.Context, current, next domain.AssessmentAttempt) error + + // SaveResult stores one typed immutable result in the same transaction as + // the completed attempt transition. + SaveResult(ctx context.Context, userID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) error + + // GetResult returns the immutable owner-scoped result snapshot. + GetResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultSnapshot, error) + + // SaveSessionOutcome records the original 200 public projection for the + // already-reserved idempotency scope. It shares the transaction and expiry + // of the generic idempotency record. + SaveSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, response domain.AssessmentAttemptPublicSnapshot) error + + // GetSessionOutcome returns the original 200 public projection for a live + // key, even if the stored attempt has since changed. + GetSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentAttemptPublicSnapshot, error) + + // SaveAnswerOutcome stores a successful answer response or deterministic + // not-found/state-conflict problem for its idempotency scope. + SaveAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error + + // GetAnswerOutcome returns the original typed answer outcome for a live key. + GetAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error) + + // SaveFinalizeOutcome stores a successful finalize response or deterministic + // not-found/state-conflict problem for its idempotency scope. + SaveFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error + + // GetFinalizeOutcome returns the original typed finalize outcome for a live key. + GetFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error) +} diff --git a/backend/internal/port/outbound/assessment_bank.go b/backend/internal/port/outbound/assessment_bank.go index ada2c85..aa7b97f 100644 --- a/backend/internal/port/outbound/assessment_bank.go +++ b/backend/internal/port/outbound/assessment_bank.go @@ -2,9 +2,12 @@ package outbound import ( "context" + "crypto/sha256" "errors" "time" + "github.com/google/uuid" + "lincodex/backend/internal/domain" ) @@ -51,6 +54,13 @@ var ( // ErrAssessmentCatalogBindingImmutable reports an attempt to edit or remove // an immutable reviewed catalog binding. ErrAssessmentCatalogBindingImmutable = errors.New("assessment catalog binding is immutable") + + // ErrAssessmentSelectionUnavailable reports that no current reviewed + // category exactly matches the requested public selection. + ErrAssessmentSelectionUnavailable = errors.New("assessment selection is unavailable") + // ErrAssessmentSelectionAmbiguous reports more than one current category + // matching the same public selection; the server never chooses arbitrarily. + ErrAssessmentSelectionAmbiguous = errors.New("assessment selection is ambiguous") ) // MaxAssessmentFamilyPageSize is the largest page that ListFamilies returns. @@ -64,6 +74,42 @@ type AssessmentFamilyCursor struct { Version int32 } +// AssessmentBankSelection is the exact reviewed category manifest used to +// build one real attempt. Families are the entries from the pinned manifest, +// not an inferred snapshot of current rows. +type AssessmentBankSelection struct { + Opening domain.AssessmentCategoryOpening + ProductPolicyVersionID domain.PolicyVersionID + ProductPolicyVersion int32 + ManifestSHA [sha256.Size]byte + Families []domain.AssessmentFamily +} + +// AssessmentTrainingBankSelection is an explicitly reviewed, non-qualification +// family set pinned to one product policy version. +type AssessmentTrainingBankSelection struct { + BindingID uuid.UUID + Category domain.AssessmentCategory + ProductPolicyVersionID domain.PolicyVersionID + ProductPolicyVersion int32 + ManifestSHA [sha256.Size]byte + Families []domain.AssessmentFamily +} + +// AssessmentAvailabilitySelection is one current, reviewed specialization, +// grade, and language binding with the family keys from its verified live +// published manifest. It exposes no task content. +type AssessmentAvailabilitySelection struct { + OpeningID uuid.UUID + Category domain.AssessmentCategory + ProductPolicyVersionID domain.PolicyVersionID + ProductPolicyVersion int32 + Specialization domain.SpecializationCode + Grade domain.GradeCode + TaskLanguages []domain.TaskLanguageCode + FamilyKeys []domain.AssessmentFamilyKey +} + // AssessmentBankRepositories exposes the assessment bank. UnitOfWork binds it // to one transaction; an adapter may also provide it outside a transaction, // where every call is its own statement. A returned family passed @@ -139,6 +185,12 @@ type AssessmentBankRepository interface { // coverage, or published-family manifest changed are omitted. ListCurrentSpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error) + // ListCurrentAssessmentAvailabilitySelections returns current, reviewed + // selection metadata pinned to the effective product policy at asOf. The + // implementation validates each live published-family manifest and does + // not take category locks or load task content. + ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf time.Time) ([]AssessmentAvailabilitySelection, error) + // DatabaseTime returns the database clock. It stamps the effective time // of a policy version, so the version in force now is judged against it // and not against the application clock. @@ -147,4 +199,22 @@ type AssessmentBankRepository interface { // GetCurrentCategoryOpening returns the newest opening of the category, // or ErrAssessmentCategoryNotOpen. GetCurrentCategoryOpening(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) + + // ResolveCurrentSelection finds exactly one current catalog binding for + // the public request, locks its category, and rechecks the opening, product + // policy, live manifest, and exact family versions under that lock. + ResolveCurrentSelection( + ctx context.Context, + specialization domain.SpecializationCode, + grade domain.GradeCode, + language *domain.TaskLanguageCode, + ) (AssessmentBankSelection, error) + + // ResolveCurrentTrainingSelection returns exactly one reviewed training + // binding whose policy pin and published family manifest remain current. + ResolveCurrentTrainingSelection( + ctx context.Context, + productPolicyID domain.PolicyVersionID, + productPolicyVersion int32, + ) (AssessmentTrainingBankSelection, error) } diff --git a/backend/internal/port/outbound/assessment_signal.go b/backend/internal/port/outbound/assessment_signal.go new file mode 100644 index 0000000..b10918b --- /dev/null +++ b/backend/internal/port/outbound/assessment_signal.go @@ -0,0 +1,26 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "lincodex/backend/internal/domain" +) + +var ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found") + +type AssessmentSignalRepositories interface { + AssessmentSignals() AssessmentSignalRepository +} + +// AssessmentSignalRepository persists event metadata and the immutable +// candidate receipt in the current unit of work. +type AssessmentSignalRepository interface { + CountRecentOutcomes(ctx context.Context, attemptID domain.AssessmentAttemptID, since time.Time) (int64, time.Time, error) + CountAttemptEvents(ctx context.Context, attemptID domain.AssessmentAttemptID) (int64, error) + SaveBatch(ctx context.Context, batch domain.AssessmentSignalBatch) error + SaveOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, attemptID domain.AssessmentAttemptID, receipt domain.AssessmentSignalReceipt) error + DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error + GetOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentSignalReceipt, error) +} diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go index ba0832e..c4f1bb9 100644 --- a/backend/internal/port/outbound/consents.go +++ b/backend/internal/port/outbound/consents.go @@ -151,6 +151,13 @@ type ConsentLedger interface { // CurrentContact. Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) + // LockCurrentForUse returns and share-locks the current C3 record for the + // subject. A caller that authorizes a real automated assessment must use it + // inside the same transaction that creates or mutates that assessment. The + // lock serializes the operation with C3 revocation until commit. Missing C3 + // returns ErrConsentNotFound; other purposes return domain.ErrInvalidConsent. + LockCurrentForUse(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) + // LockRegistration returns and locks the active registration C1 for one // registration version, or ErrConsentNotFound. Email confirmation calls it // inside the same transaction after consuming the token and applying the diff --git a/backend/internal/port/outbound/needs.go b/backend/internal/port/outbound/needs.go index edbe067..3d804c2 100644 --- a/backend/internal/port/outbound/needs.go +++ b/backend/internal/port/outbound/needs.go @@ -3,6 +3,7 @@ package outbound import ( "context" "errors" + "time" "github.com/google/uuid" @@ -21,12 +22,21 @@ var ( // surrounding transaction remains safe to roll back and the API maps the // conflict to its current 412 contract. ErrNeedVersionConflict = errors.New("organization need changed concurrently") + + // ErrNeedCreationResultNotFound reports a missing immutable response for a + // live idempotency record. + ErrNeedCreationResultNotFound = errors.New("organization need creation result not found") ) +// MaxNeedPageSize is the largest organization-scoped page in the contract. +const MaxNeedPageSize = 100 + // NeedRepositories exposes tenant-scoped need storage bound to one // UnitOfWork transaction. type NeedRepositories interface { Needs() NeedRepository + NeedLists() NeedListRepository + NeedCreationResults() NeedCreationResultRepository } // NeedRepository stores the current organization need and its immutable @@ -48,3 +58,40 @@ type NeedRepository interface { // rolls back both writes if either write fails. Save(ctx context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error } + +// NeedListRepository reads one bounded, organization-scoped page of needs. +type NeedListRepository interface { + List(ctx context.Context, query NeedListQuery) (NeedPage, error) +} + +// NeedCreationResultRepository stores the immutable public result produced by +// a successful idempotent create command. The scope references the generic +// idempotency record, so it is removed when that record is purged. +type NeedCreationResultRepository interface { + SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error + GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error) +} + +// NeedListQuery selects one page within a single organization. +type NeedListQuery struct { + OrganizationID uuid.UUID + After *NeedListPosition + Limit int32 +} + +// NeedListPosition is the stable newest-first ordering key for pagination. +type NeedListPosition struct { + CreatedAt time.Time + NeedID uuid.UUID +} + +// NeedPage contains one organization-scoped page of needs. +type NeedPage struct { + Items []domain.Need + HasMore bool +} + +// NeedCreationPosition returns the pagination key for one need. +func NeedCreationPosition(need domain.Need) NeedListPosition { + return NeedListPosition{CreatedAt: need.CreatedAt(), NeedID: need.ID()} +} diff --git a/backend/internal/port/outbound/organizations.go b/backend/internal/port/outbound/organizations.go index f429775..ca140cb 100644 --- a/backend/internal/port/outbound/organizations.go +++ b/backend/internal/port/outbound/organizations.go @@ -87,6 +87,14 @@ type OrganizationRepository interface { // suspended, removed, or left. GetForMember(ctx context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error) + // LockActiveMembership locks the organization row first, then the active + // membership row, through the surrounding transaction. Writers that act on + // owner access use it to serialize against membership revocation and keep + // the same organization-then-membership lock order as profile updates. It + // returns ErrOrganizationNotFound for an unknown organization or an + // account without an active membership. + LockActiveMembership(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) + // ListForUser returns one page of the organizations where the account has // an active membership, newest membership first. ListForUser(ctx context.Context, query OrganizationListQuery) (OrganizationPage, error) diff --git a/backend/internal/port/outbound/privacy_cohort.go b/backend/internal/port/outbound/privacy_cohort.go new file mode 100644 index 0000000..a4e791a --- /dev/null +++ b/backend/internal/port/outbound/privacy_cohort.go @@ -0,0 +1,21 @@ +package outbound + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ErrPrivacyCohortUnavailable = errors.New("anonymous candidate cohort unavailable") + +// PrivacyCohortRepository reads the candidates eligible for one +// organization-scoped anonymous projection. The caller must first authorize +// an active organization membership. The adapter must select from +// candidate_effective_publications and exclude the reading organization's +// hidden candidates in the same SQL statement. +type PrivacyCohortRepository interface { + ListVisibleCandidateViewSources(ctx context.Context, organizationID uuid.UUID) ([]domain.CandidateViewSource, error) +} diff --git a/backend/internal/port/outbound/privacy_settings.go b/backend/internal/port/outbound/privacy_settings.go new file mode 100644 index 0000000..8f6545e --- /dev/null +++ b/backend/internal/port/outbound/privacy_settings.go @@ -0,0 +1,110 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + ErrCandidatePrivacySettingsNotFound = errors.New("candidate privacy settings not found") + ErrCandidatePrivacyOrganizationNotVisible = errors.New("organization is not visible to candidate") + ErrCandidateHiddenOrganizationLimit = errors.New("candidate hidden organization limit reached") +) + +const MaxPrivacyPageSize = 100 + +// CandidatePrivacySettings is the candidate-owned visibility snapshot from +// one repository read. +type CandidatePrivacySettings struct { + Publication domain.Publication + SearchStatus domain.SearchStatus + HiddenCount int64 + AsOf time.Time +} + +// CandidateVisibleOrganization contains only the public organization details +// that a candidate may already read. +type CandidateVisibleOrganization struct { + ID uuid.UUID + Name string +} + +// HiddenOrganizationRecord is one owner-visible hiding and its current public +// organization name. +type HiddenOrganizationRecord struct { + OrganizationID uuid.UUID + OrganizationName string + HiddenAt time.Time +} + +type HiddenOrganizationListQuery struct { + UserID uuid.UUID + After *HiddenOrganizationPosition + Limit int32 +} + +type HiddenOrganizationPosition struct { + HiddenAt time.Time + OrganizationID uuid.UUID +} + +type HiddenOrganizationPage struct { + Items []HiddenOrganizationRecord + HasMore bool +} + +type CandidatePrivacyEventRecord struct { + ID uuid.UUID + Kind domain.PrivacyEventKind + OccurredAt time.Time + Fields *domain.CardFieldSet + ConsentRecordID uuid.UUID + OrganizationID uuid.UUID + OrganizationName string +} + +type CandidatePrivacyEventListQuery struct { + UserID uuid.UUID + After *CandidatePrivacyEventPosition + Limit int32 +} + +type CandidatePrivacyEventPosition struct { + OccurredAt time.Time + ID uuid.UUID +} + +type CandidatePrivacyEventPage struct { + Items []CandidatePrivacyEventRecord + HasMore bool +} + +// PrivacySettingsRepository reads and changes only a candidate's visibility +// settings. Mutation methods are transaction-bound through UnitOfWork. +type PrivacySettingsRepository interface { + ReadSettings(ctx context.Context, userID uuid.UUID) (CandidatePrivacySettings, error) + LockCurrentC2ForPublication(ctx context.Context, userID uuid.UUID) (uuid.UUID, error) + SavePublication(ctx context.Context, publication domain.Publication, expectedVersion int64) error + SaveSearchStatus(ctx context.Context, status domain.SearchStatus, expectedVersion int64, at time.Time) error + CountHiddenOrganizations(ctx context.Context, userID uuid.UUID) (int64, error) + GetHiddenOrganization(ctx context.Context, userID, organizationID uuid.UUID) (HiddenOrganizationRecord, error) + CandidateCanSeeOrganization(ctx context.Context, userID, organizationID uuid.UUID) (CandidateVisibleOrganization, error) + HideOrganization(ctx context.Context, hidden domain.HiddenOrganization) (created bool, err error) + UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (deleted bool, err error) + ListHiddenOrganizations(ctx context.Context, query HiddenOrganizationListQuery) (HiddenOrganizationPage, error) + RecordPrivacyEvent(ctx context.Context, event domain.PrivacyEvent) error + ListPrivacyEvents(ctx context.Context, query CandidatePrivacyEventListQuery) (CandidatePrivacyEventPage, error) +} + +func HiddenOrganizationPositionOf(record HiddenOrganizationRecord) HiddenOrganizationPosition { + return HiddenOrganizationPosition{HiddenAt: record.HiddenAt, OrganizationID: record.OrganizationID} +} + +func CandidatePrivacyEventPositionOf(record CandidatePrivacyEventRecord) CandidatePrivacyEventPosition { + return CandidatePrivacyEventPosition{OccurredAt: record.OccurredAt, ID: record.ID} +} diff --git a/backend/internal/port/outbound/privacy_view.go b/backend/internal/port/outbound/privacy_view.go new file mode 100644 index 0000000..8b5b39d --- /dev/null +++ b/backend/internal/port/outbound/privacy_view.go @@ -0,0 +1,107 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + ErrCandidateCardAccessNotFound = errors.New("candidate card access not found") + ErrCandidateC2Unavailable = errors.New("candidate C2 publication is unavailable") + ErrContactAccessClosed = errors.New("contact access is closed") +) + +const MaxCandidateCardAccessPageSize = 100 + +// PrivacyViewRepository adds the transaction-bound locks, owner preview, and +// access audit operations needed by candidate-card reads. Employer reads must +// lock candidate state in this order: account, current C2, publication. +type PrivacyViewRepository interface { + PrivacyCohortRepository + ContactAccessRepository + + // LockCandidateAccountForView conflicts with the account lock used by the + // hidden-organization limit trigger. It keeps a hide from committing while + // a card read is authorized. + LockCandidateAccountForView(ctx context.Context, candidateID uuid.UUID) error + + // LockCurrentC2ForView returns and share-locks the newest active C2 record. + // Revocation either completes before this call and is observed as missing, + // or waits until the read transaction commits. + LockCurrentC2ForView(ctx context.Context, candidateID uuid.UUID) (uuid.UUID, error) + + // LockVisiblePublicationForView share-locks the publication and its C2 row + // only while the candidate remains published, backed by c2RecordID, and + // not hidden from organizationID. + LockVisiblePublicationForView(ctx context.Context, organizationID, candidateID, c2RecordID uuid.UUID) (bool, error) + + // LockPublicationForPreview locks the candidate's currently effective own + // publication without applying any employer hiding or cohort context. + LockPublicationForPreview(ctx context.Context, candidateID uuid.UUID) (bool, error) + + // ReadCandidateViewSourceForPreview reads the current private projection + // inputs after the caller locks the effective C2 and publication. + ReadCandidateViewSourceForPreview(ctx context.Context, candidateID uuid.UUID) (domain.CandidateViewSource, error) + + // RecordCandidateCardAccess appends the access audit in the same transaction + // as the quota reservation and visibility check. + RecordCandidateCardAccess(ctx context.Context, access domain.CandidateCardAccess) error + + // ListCandidateCardAccess returns one owner-scoped page, newest first. + ListCandidateCardAccess(ctx context.Context, query CandidateCardAccessListQuery) (CandidateCardAccessListPage, error) +} + +// ContactAccessRepository is the transaction-bound final read boundary for +// contact values. The implementation must lock the current invitation grant +// and its matching C4 through the caller's transaction, then return only the +// allowlisted fields. A workflow status is never evidence of a grant. +type ContactAccessRepository interface { + CurrentFields(ctx context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) + // CloseForVisibility synchronously closes current grants for the candidate + // and, when organizationID is nonzero, only that organization. It must run + // in the same transaction as the visibility change. A later publication or + // unhide never reopens a closed grant. + CloseForVisibility(ctx context.Context, candidateID, organizationID uuid.UUID, at time.Time) error +} + +// ClosedContactAccessRepository is the production default until the separate +// invitation-grant persistence is implemented. +type ClosedContactAccessRepository struct{} + +func (ClosedContactAccessRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) { + return domain.ContactFieldSet{}, ErrContactAccessClosed +} + +func (ClosedContactAccessRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error { + return nil +} + +// CandidateCardAccessListQuery selects one candidate-owned history page. +type CandidateCardAccessListQuery struct { + CandidateID uuid.UUID + After *CandidateCardAccessPosition + Limit int32 +} + +// CandidateCardAccessPosition is the descending access history key. +type CandidateCardAccessPosition struct { + OccurredAt time.Time + ID uuid.UUID +} + +// CandidateCardAccessListPage is one page of the candidate's access history. +type CandidateCardAccessListPage struct { + Items []domain.CandidateCardAccess + OrganizationNames map[uuid.UUID]string + HasMore bool +} + +// CandidateCardAccessPositionOf creates the continuation key for an event. +func CandidateCardAccessPositionOf(access domain.CandidateCardAccess) CandidateCardAccessPosition { + return CandidateCardAccessPosition{OccurredAt: access.OccurredAt(), ID: access.ID()} +} diff --git a/backend/internal/port/outbound/support_cases.go b/backend/internal/port/outbound/support_cases.go new file mode 100644 index 0000000..b0b80a5 --- /dev/null +++ b/backend/internal/port/outbound/support_cases.go @@ -0,0 +1,159 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrSupportCaseNotFound covers both an unknown case and one owned by + // another account. + ErrSupportCaseNotFound = errors.New("support case not found") + + // ErrSupportCaseCreateOutcomeNotFound reports a live idempotency record + // without its immutable create result. It is an integrity error, not a + // public 404 response. + ErrSupportCaseCreateOutcomeNotFound = errors.New("support case create outcome not found") + + // ErrSupportCaseConflict reports an appeal or another case that conflicts + // with a still-current business rule. The repository leaves the + // transaction usable so the caller can persist the immutable 409 outcome. + ErrSupportCaseConflict = errors.New("support case conflicts with existing state") +) + +// MaxSupportCasePageSize matches the largest list page in the API contract. +const MaxSupportCasePageSize = 100 + +// SupportCaseRepositories groups the ports that a create transaction must +// bind to one unit of work. The caller also uses the existing idempotency +// repository in that same transaction. +type SupportCaseRepositories interface { + SupportCases() SupportCaseRepository + SupportCaseCreateOutcomes() SupportCaseCreateOutcomeRepository + SupportCaseRequestLimits() SupportCaseRequestLimitRepository + SupportCaseRubrics() SupportCaseRubricRepository +} + +// SupportCaseRepository stores owner-private snapshots and their public +// history. Implementations persist only the typed object reference, not a +// copy of the referenced object, and every read names the owning account. +type SupportCaseRepository interface { + // NextNumber allocates a globally unique, never-reused display number for + // the UTC year containing createdAt. The number is for display; case paths + // use the UUID identifier. + NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) + + // Create inserts the case and its complete initial public history in the + // surrounding transaction. A failed create leaves neither committed. + Create(ctx context.Context, supportCase domain.SupportCase) error + + // GetOwned returns the full case only when ownerID matches. Unknown and + // foreign IDs both return ErrSupportCaseNotFound. + GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) + + // ListOwned returns one page of summaries for ownerID, newest first by + // CreatedAt and then ID. It never returns descriptions or event history. + ListOwned(ctx context.Context, query SupportCaseListQuery) (SupportCaseListPage, error) +} + +// SupportCaseCreateOutcomeRepository persists the original response for a +// live generic idempotency scope. The stored case snapshot is immutable even +// if the case later receives replies or changes status. +type SupportCaseCreateOutcomeRepository interface { + // DeleteCreateOutcome removes the expired result for a scope that the + // generic idempotency repository has just accepted as new. It must run in + // the same transaction as the replacement command. + DeleteCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) error + + // SaveCreateOutcome stores a 201, 404, or domain state_conflict 409 result + // in the surrounding transaction. Rejected validation, CSRF, rate-limit, + // idempotency-in-progress, and key-reuse responses are not stored. The + // scope is the HMAC digest from Idempotency-Key handling; raw keys and + // request content never reach this port. + SaveCreateOutcome( + ctx context.Context, + scope [IdempotencyDigestSize]byte, + outcome domain.SupportCaseCreateOutcome, + createdAt time.Time, + ) error + + // GetCreateOutcome returns the original result for a live idempotency + // scope, or ErrSupportCaseCreateOutcomeNotFound if the record is incomplete. + GetCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.SupportCaseCreateOutcome, error) +} + +// SupportCaseRequestLimitRepository enforces the per-account rolling request +// budget. It is called after authentication, request validation, and account +// scenario checks but before idempotency lookup or object resolution, so an +// accepted replay and requests ending in 404 or 409 consume the same budget. +// Implementations retain accepted request events for at least +// domain.MaxSupportRequestWindow, even when the current product policy uses a +// shorter window, so a later policy version can widen the window safely. +// The use case must commit this counter for domain-level 400 and idempotency +// 422 results that occur after this check, while leaving their create outcome +// unstored; it returns those expected results as data and maps them to HTTP +// only after the unit of work commits. +type SupportCaseRequestLimitRepository interface { + // LockOwner serializes the account's request-budget check before the + // application timestamp is captured. The lock lasts until the enclosing + // unit of work commits or rolls back. It returns the latest committed + // request timestamp, or zero when the account has no request history, so a + // temporarily regressing application clock cannot move the effective + // window behind an event already counted. + LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) + + // Consume records one qualifying request when the preceding rolling + // window has fewer than maxRequests. The caller must acquire LockOwner + // before supplying at. It returns Allowed=false and a + // positive RetryAfter when the budget is exhausted. Rejected over-limit + // requests do not increment the counter. Count only events with + // requested_at > at-window and requested_at <= at; calculate RetryAfter + // from the oldest event included in that count. + Consume( + ctx context.Context, + ownerID uuid.UUID, + at time.Time, + maxRequests int32, + window time.Duration, + ) (SupportCaseRequestLimitResult, error) +} + +// SupportCaseRequestLimitResult describes whether this request consumed a +// slot in the account's rolling request budget. +type SupportCaseRequestLimitResult struct { + Allowed bool + RetryAfter time.Duration +} + +// SupportCaseListQuery selects one owner-scoped page. +type SupportCaseListQuery struct { + OwnerID uuid.UUID + // After continues after the last item from the preceding page; nil reads + // the newest cases. + After *SupportCaseListPosition + // Limit is from 1 to MaxSupportCasePageSize. + Limit int32 +} + +// SupportCaseListPosition is the descending order key for one list item. +type SupportCaseListPosition struct { + CreatedAt time.Time + ID domain.SupportCaseID +} + +// SupportCaseListPage is one page of summaries. HasMore is true when another +// page follows and the caller can continue from the last item's position. +type SupportCaseListPage struct { + Items []domain.SupportCaseSummary + HasMore bool +} + +// SupportCasePositionOf returns the cursor position of an item from a page. +func SupportCasePositionOf(item domain.SupportCaseSummary) SupportCaseListPosition { + return SupportCaseListPosition{CreatedAt: item.CreatedAt, ID: item.ID} +} diff --git a/backend/internal/port/outbound/support_rubrics.go b/backend/internal/port/outbound/support_rubrics.go new file mode 100644 index 0000000..1777fec --- /dev/null +++ b/backend/internal/port/outbound/support_rubrics.go @@ -0,0 +1,29 @@ +package outbound + +import ( + "context" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// SupportCaseRubric pins a manual request to the same grading-policy version +// and reviewed category opening used by automated assessment. +type SupportCaseRubric struct { + Version int32 + OpeningID uuid.UUID + PolicyVersionID domain.PolicyVersionID +} + +// SupportCaseRubricRepository resolves a rubric for manual assessment cases. +// A case has no task-language field, so implementations match all current +// reviewed catalog bindings for its exact specialization and grade. They +// return nil when no unique current opening matches. +type SupportCaseRubricRepository interface { + ResolveCurrent( + ctx context.Context, + specialization domain.SpecializationCode, + grade domain.GradeCode, + ) (*SupportCaseRubric, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 4603fbb..7d36883 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -45,6 +45,13 @@ type Transactor interface { WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error } +// ReadOnlySnapshotTransactor runs one read operation against a consistent, +// read-only database snapshot. It is separate from Transactor so write +// usecases and their implementations do not silently change isolation. +type ReadOnlySnapshotTransactor interface { + WithinReadOnlySnapshot(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error +} + // UnitOfWork exposes repositories bound to one transaction. Product // repositories are added here as their usecases appear. type UnitOfWork interface { @@ -52,12 +59,18 @@ type UnitOfWork interface { ConsentRepositories CandidateProfileRepositories CandidateQuestionnaireRepositories + PrivacyCohort() PrivacyCohortRepository + PrivacyView() PrivacyViewRepository + PrivacySettings() PrivacySettingsRepository AccountDeletionRequests() AccountDeletionRequests ConsentRevocationEffects() ConsentRevocationEffects OrganizationRepositories NeedRepositories CompanyQuotas() CompanyQuotaRepository AssessmentBankRepositories + AssessmentAttemptRepositories + AssessmentSignalRepositories + SupportCaseRepositories Policies() PolicyRepository Deliveries() DeliveryRepository MailRequests() MailRequestRepository diff --git a/backend/internal/usecase/anonymousprofile/service.go b/backend/internal/usecase/anonymousprofile/service.go new file mode 100644 index 0000000..6a79b1c --- /dev/null +++ b/backend/internal/usecase/anonymousprofile/service.go @@ -0,0 +1,121 @@ +// Package anonymousprofile builds organization-scoped, privacy-preserving +// projections from the candidates that the storage adapter has already +// filtered by effective publication and hidden-organization state. +package anonymousprofile + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ErrInvalidOrganization = errors.New("anonymous profile organization is invalid") + +type Service struct { + reader outbound.PrivacyCohortRepository + key domain.CandidateViewPseudonymKey + clock func() time.Time +} + +func NewService(reader outbound.PrivacyCohortRepository, key domain.CandidateViewPseudonymKey, clock func() time.Time) *Service { + if reader == nil { + panic("anonymousprofile.NewService - reader must not be nil") + } + if clock == nil { + panic("anonymousprofile.NewService - clock must not be nil") + } + return &Service{reader: reader, key: key, clock: clock} +} + +// ListVisible returns only candidates whose complete generalized visible +// cohort has at least five members. Active organization membership is checked +// by the caller; the repository independently enforces publication and +// organization hiding in one read statement. +func (service *Service) ListVisible(ctx context.Context, organizationID uuid.UUID) ([]domain.AnonymousCandidateViewDTO, error) { + const location = "anonymousprofile.Service.ListVisible" + if organizationID == uuid.Nil { + return nil, fmt.Errorf("%s - organization ID must be set: %w", location, ErrInvalidOrganization) + } + sources, err := service.reader.ListVisibleCandidateViewSources(ctx, organizationID) + if err != nil { + return nil, fmt.Errorf("%s - read visible candidate sources: %w", location, err) + } + return service.ProjectSources(organizationID, sources) +} + +// ProjectSources builds a generalized view from a caller-provided current +// source snapshot. A transactional reader can lock the source rows first and +// reuse that exact snapshot without issuing a second, potentially newer query. +func (service *Service) ProjectSources( + organizationID uuid.UUID, + sources []domain.CandidateViewSource, +) ([]domain.AnonymousCandidateViewDTO, error) { + const location = "anonymousprofile.Service.ProjectSources" + if organizationID == uuid.Nil { + return nil, fmt.Errorf("%s - organization ID must be set: %w", location, ErrInvalidOrganization) + } + asOf := service.clock().UTC() + if asOf.IsZero() { + return nil, fmt.Errorf("%s - clock returned zero: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + views := make([]domain.AnonymousCandidateView, 0, len(sources)) + seenCandidates := make(map[uuid.UUID]struct{}, len(sources)) + for _, source := range sources { + if err := domain.ValidateCandidateViewSource(source); err != nil { + return nil, fmt.Errorf("%s - source is invalid: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + candidateID := source.CandidateID() + if _, duplicate := seenCandidates[candidateID]; duplicate { + return nil, fmt.Errorf("%s - source list contains a duplicate candidate: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + seenCandidates[candidateID] = struct{}{} + pseudonym, err := service.key.ForOrganization(organizationID, candidateID) + if err != nil { + return nil, fmt.Errorf("%s - derive candidate alias: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + view, err := domain.NewAnonymousCandidateView(source.Input(pseudonym, asOf)) + if err != nil { + return nil, fmt.Errorf("%s - build candidate projection: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + views = append(views, view) + } + var err error + views, err = domain.GeneralizeAnonymousCandidateCohort(views) + if err != nil { + return nil, fmt.Errorf("%s - generalize visible cohort: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + result := make([]domain.AnonymousCandidateViewDTO, 0, len(views)) + for _, view := range views { + result = append(result, view.DTO()) + } + return result, nil +} + +// PreviewSource builds the candidate's private card preview with a purpose- +// separated alias. It does not apply an organization cohort because no +// organization context exists for this read. +func (service *Service) PreviewSource(source domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error) { + const location = "anonymousprofile.Service.PreviewSource" + if err := domain.ValidateCandidateViewSource(source); err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - source is invalid: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + asOf := service.clock().UTC() + if asOf.IsZero() { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - clock returned zero: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + pseudonym, err := service.key.ForCandidatePreview(source.CandidateID()) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - derive preview alias: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + view, err := domain.NewAnonymousCandidateView(source.Input(pseudonym, asOf)) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build candidate preview: %w", location, err) + } + return view.DTO(), nil +} diff --git a/backend/internal/usecase/anonymousprofile/service_test.go b/backend/internal/usecase/anonymousprofile/service_test.go new file mode 100644 index 0000000..8b1350f --- /dev/null +++ b/backend/internal/usecase/anonymousprofile/service_test.go @@ -0,0 +1,133 @@ +package anonymousprofile + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +type privacyCohortReaderFunc func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) + +func (reader privacyCohortReaderFunc) ListVisibleCandidateViewSources(ctx context.Context, organizationID uuid.UUID) ([]domain.CandidateViewSource, error) { + return reader(ctx, organizationID) +} + +func TestListVisibleReturnsOrganizationScopedAliasesAndSuppressesSmallCohort(t *testing.T) { + t.Parallel() + + organizationID := uuid.New() + candidateIDs := make([]uuid.UUID, 5) + sources := make([]domain.CandidateViewSource, 0, len(candidateIDs)) + fields, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldStack}) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + for index := range candidateIDs { + candidateIDs[index] = uuid.New() + profile, err := domain.EmptyCandidateProfile(candidateIDs[index]) + if err != nil { + t.Fatalf("EmptyCandidateProfile() error = %v", err) + } + source, err := domain.NewCandidateViewSource( + candidateIDs[index], fields, domain.CandidateViewProfileFromContent(profile.Content()), nil, nil, nil, + ) + if err != nil { + t.Fatalf("NewCandidateViewSource() error = %v", err) + } + sources = append(sources, source) + } + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("purpose-specific-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + service := NewService(privacyCohortReaderFunc(func(_ context.Context, got uuid.UUID) ([]domain.CandidateViewSource, error) { + if got != organizationID { + t.Fatalf("reader organization = %s, want %s", got, organizationID) + } + return sources, nil + }), key, func() time.Time { return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) }) + + views, err := service.ListVisible(context.Background(), organizationID) + if err != nil { + t.Fatalf("ListVisible() error = %v", err) + } + if len(views) != 5 { + t.Fatalf("ListVisible() returned %d views, want five", len(views)) + } + aliases := make([]string, 0, len(views)) + for _, view := range views { + aliases = append(aliases, view.Pseudonym) + } + seenAliases := make(map[string]struct{}, len(aliases)) + for _, alias := range aliases { + if _, duplicate := seenAliases[alias]; duplicate { + t.Fatalf("pseudonyms are not unique within the organization: %v", aliases) + } + seenAliases[alias] = struct{}{} + } + encoded, err := json.Marshal(views) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + for _, candidateID := range candidateIDs { + if bytes.Contains(encoded, []byte(candidateID.String())) { + t.Fatalf("organization-facing projection contains source ID %s", candidateID) + } + } + + otherOrganization := uuid.New() + otherService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) { + return sources, nil + }), key, func() time.Time { return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) }) + otherViews, err := otherService.ListVisible(context.Background(), otherOrganization) + if err != nil { + t.Fatalf("ListVisible(other organization) error = %v", err) + } + if otherViews[0].Pseudonym == views[0].Pseudonym { + t.Fatal("candidate pseudonym was reused across organizations") + } + + smallService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) { + return sources[:4], nil + }), key, time.Now) + small, err := smallService.ListVisible(context.Background(), organizationID) + if err != nil { + t.Fatalf("ListVisible(small cohort) error = %v", err) + } + if len(small) != 0 { + t.Fatalf("small cohort returned %d views, want suppression", len(small)) + } +} + +func TestListVisibleRejectsInvalidScopeAndSourceFailures(t *testing.T) { + t.Parallel() + + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("purpose-specific-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + service := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) { + return nil, errors.New("storage unavailable") + }), key, time.Now) + if _, err := service.ListVisible(context.Background(), uuid.Nil); !errors.Is(err, ErrInvalidOrganization) { + t.Fatalf("ListVisible(empty organization) error = %v, want ErrInvalidOrganization", err) + } + if _, err := service.ListVisible(context.Background(), uuid.New()); err == nil || !strings.Contains(err.Error(), "read visible candidate sources") { + t.Fatalf("ListVisible(storage error) = %v, want wrapped read error", err) + } + + invalidSourceService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) { + return []domain.CandidateViewSource{{}}, nil + }), key, time.Now) + if _, err := invalidSourceService.ListVisible(context.Background(), uuid.New()); !errors.Is(err, domain.ErrInvalidAnonymousCandidateView) { + t.Fatalf("ListVisible(invalid source) error = %v, want invalid projection", err) + } +} diff --git a/backend/internal/usecase/assessment/answer.go b/backend/internal/usecase/assessment/answer.go new file mode 100644 index 0000000..00a6b93 --- /dev/null +++ b/backend/internal/usecase/assessment/answer.go @@ -0,0 +1,231 @@ +package assessment + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const submitAnswerOperation = "assessment_attempt.answer" + +// SubmitAttemptAnswerCommand is one candidate answer to the current frozen +// item. The answer is private and must not be logged. +type SubmitAttemptAnswerCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + ItemID uuid.UUID + ExpectedVersion int64 + IdempotencyKey string + Answer json.RawMessage +} + +type canonicalAttemptAnswerBody struct { + AttemptID string `json:"attempt_id"` + ItemID string `json:"item_id"` + ExpectedVersion int64 `json:"expected_version"` + Answer json.RawMessage `json:"answer"` +} + +// SubmitAnswer persists the current answer and an immutable public response in +// one transaction. Raw answer data never enters the idempotency table. +func (service *AttemptService) SubmitAnswer( + ctx context.Context, + command SubmitAttemptAnswerCommand, +) (outbound.AssessmentAttemptCommandResult, error) { + const location = "AttemptService.SubmitAnswer" + if command.ActorID == uuid.Nil { + return outbound.AssessmentAttemptCommandResult{}, ErrAttemptForbidden + } + if command.AttemptID.IsZero() || command.ItemID == uuid.Nil || command.ExpectedVersion < 1 { + return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/expected_version", "must be a positive version and identify one item") + } + canonicalAnswer, err := domain.CanonicalAssessmentAnswer(command.Answer) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/answer", "must match a supported answer format") + } + body, err := json.Marshal(canonicalAttemptAnswerBody{ + AttemptID: command.AttemptID.String(), ItemID: command.ItemID.String(), ExpectedVersion: command.ExpectedVersion, + Answer: canonicalAnswer, + }) + if err != nil || len(body) > maxAttemptCanonicalBodyBytes { + return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest + } + keyTime, err := assessmentIdempotencyTime(service.clock()) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err) + } + request, err := service.prepareAttemptIdempotency(submitAnswerOperation, command.IdempotencyKey, command.ActorID, body, keyTime) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err) + } + var result outbound.AssessmentAttemptCommandResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { + return err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return fmt.Errorf("%s - reserve idempotency: %w", location, err) + } + repository := unit.AssessmentAttempts() + if !created { + return replayAttemptAnswer(ctx, repository, request, stored, &result) + } + if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil { + return fmt.Errorf("%s - remove expired answer response: %w", location, err) + } + return service.submitNewAnswer(ctx, unit, repository, request.scope, command, &result) + }) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func replayAttemptAnswer( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + request attemptIdempotencyRequest, + stored outbound.IdempotencyRecord, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "assessment.replayAttemptAnswer" + if stored.Fingerprint != request.record.Fingerprint { + return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) + } + outcome, err := repository.GetAnswerOutcome(ctx, request.scope) + if err != nil { + return fmt.Errorf("%s - read immutable answer response: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true} + return nil +} + +func (service *AttemptService) submitNewAnswer( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command SubmitAttemptAnswerCommand, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.submitNewAnswer" + current, err := lockAttemptForAnswer(ctx, unit, repository, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return storeAttemptCommandProblem(ctx, repository, scope, "answer", 404, result) + } + if err != nil { + return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if !attemptHasItem(current, command.ItemID) { + return attemptFieldError("/item_id", "does not identify an item in this attempt") + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result) +} + +func lockAttemptForAnswer( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentAttemptRepository, + actorID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttempt, error) { + const location = "AttemptService.lockAttemptForAnswer" + kind, err := repository.GetKindForCandidate(ctx, actorID, attemptID) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) + } + if err := lockSessionConsent(ctx, unit, actorID, kind); err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize answer: %w", location, err) + } + current, err := repository.GetForCandidateForUpdate(ctx, actorID, attemptID) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if current.Kind() != kind { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return current, nil +} + +func (service *AttemptService) persistSubmittedAnswer( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command SubmitAttemptAnswerCommand, + current domain.AssessmentAttempt, + databaseTime time.Time, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.persistSubmittedAnswer" + updated, changed, submitErr := current.SubmitAnswer(command.ExpectedVersion, command.ItemID, command.Answer, databaseTime) + if submitErr != nil && errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) && command.ExpectedVersion == current.Version() { + expired, expiredChanged, expireErr := current.ExpireIfDue(databaseTime) + if expireErr != nil { + return fmt.Errorf("%s - apply due deadline transition: %w", location, expireErr) + } + if expiredChanged { + if err := repository.SaveTransition(ctx, current, expired); err != nil { + return fmt.Errorf("%s - persist due deadline transition: %w", location, err) + } + return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result) + } + } + if submitErr != nil { + if errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) { + return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result) + } + return mapAttemptAnswerError(submitErr) + } + if changed { + if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil { + return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err) + } + } + outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()} + if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store immutable answer response: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} + return nil +} + +func attemptHasItem(attempt domain.AssessmentAttempt, itemID uuid.UUID) bool { + for _, item := range attempt.Snapshot().Items { + if item.ID == itemID { + return true + } + } + return false +} + +func mapAttemptAnswerError(err error) error { + switch { + case errors.Is(err, domain.ErrAssessmentAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict): + return fmt.Errorf("AttemptService.SubmitAnswer - check expected version: %w", ErrAttemptVersionConflict) + case errors.Is(err, domain.ErrAssessmentAttemptNotActive): + return fmt.Errorf("AttemptService.SubmitAnswer - check answer state: %w", ErrAttemptStateConflict) + case errors.Is(err, domain.ErrInvalidAssessmentAttempt): + return attemptFieldError("/answer", "does not match the current item") + default: + return err + } +} diff --git a/backend/internal/usecase/assessment/attempt.go b/backend/internal/usecase/assessment/attempt.go new file mode 100644 index 0000000..c9d5c82 --- /dev/null +++ b/backend/internal/usecase/assessment/attempt.go @@ -0,0 +1,1120 @@ +package assessment + +import ( + "context" + cryptorand "crypto/rand" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math/big" + "slices" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + createAttemptOperation = "assessment_attempt.create" + startSessionOperation = "assessment_attempt.session" + maxAttemptIdempotencyKeyBytes = 255 + maxAttemptCanonicalBodyBytes = 1 << 20 + attemptAlgorithmVersion = "assessment.v1" + attemptVariantLimit = 100 +) + +var ( + ErrAttemptForbidden = errors.New("assessment attempt operation forbidden") + ErrAttemptEmailNotVerified = errors.New("assessment attempt requires a confirmed email") + ErrAttemptConsentRequired = errors.New("automated assessment consent is required") + ErrInvalidAttemptRequest = errors.New("invalid assessment attempt request") + ErrInvalidAttemptKey = errors.New("invalid assessment attempt idempotency key") + ErrAttemptKeyReused = errors.New("assessment attempt idempotency key was reused") + ErrAttemptNotFound = errors.New("assessment attempt not found") + ErrAttemptVersionConflict = errors.New("assessment attempt version changed") + ErrAttemptStateConflict = errors.New("assessment attempt state does not allow this command") +) + +// Keyring computes scoped idempotency digests with the server's shared secret. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// AttemptFieldError names a request field without retaining or echoing its value. +type AttemptFieldError struct { + Pointer string + Reason string +} + +func (fieldError *AttemptFieldError) Error() string { + return "assessment attempt field " + fieldError.Pointer + " " + fieldError.Reason +} + +func (fieldError *AttemptFieldError) Unwrap() error { return ErrInvalidAttemptRequest } + +// AttemptService creates, reads, and resumes candidate-owned attempts. +type AttemptService struct { + transactor outbound.Transactor + snapshotExecutor outbound.ReadOnlySnapshotTransactor + keyring Keyring + clock func() time.Time +} + +// NewAttemptService fails at startup when a required dependency is missing. +func NewAttemptService( + transactor outbound.Transactor, + snapshotExecutor outbound.ReadOnlySnapshotTransactor, + keyring Keyring, + clock func() time.Time, +) (*AttemptService, error) { + if transactor == nil || snapshotExecutor == nil || keyring == nil || clock == nil { + return nil, errors.New("assessment.NewAttemptService - every dependency must be set") + } + return &AttemptService{ + transactor: transactor, snapshotExecutor: snapshotExecutor, keyring: keyring, clock: clock, + }, nil +} + +// CreateAttemptCommand is one of the three disjoint public request shapes. +// All values are private candidate data and must not be logged. +type CreateAttemptCommand struct { + ActorID uuid.UUID + IdempotencyKey string + Kind domain.AssessmentAttemptKind + Specialization *domain.SpecializationCode + TargetGrade *domain.GradeCode + TaskLanguage *domain.TaskLanguageCode + RootAttemptID domain.AssessmentAttemptID +} + +type canonicalAttemptCreateBody struct { + Kind domain.AssessmentAttemptKind `json:"kind"` + Specialization *domain.SpecializationCode `json:"specialization"` + TargetGrade *domain.GradeCode `json:"target_grade"` + TaskLanguage *domain.TaskLanguageCode `json:"task_language"` + RootAttemptID string `json:"root_attempt_id,omitempty"` +} + +// CreateAttempt returns the immutable 201 or 409 response retained for the +// idempotency window. Request validation errors roll back the reservation. +func (service *AttemptService) CreateAttempt( + ctx context.Context, + command CreateAttemptCommand, +) (outbound.AssessmentAttemptCreateResult, error) { + const location = "AttemptService.CreateAttempt" + body, err := canonicalizeAttemptCreateBody(command) + if err != nil { + return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - validate request: %w", location, err) + } + keyTime, err := assessmentIdempotencyTime(service.clock()) + if err != nil { + return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - validate application time: %w", location, err) + } + var result outbound.AssessmentAttemptCreateResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { + return err + } + request, err := service.prepareAttemptIdempotency(createAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime) + if err != nil { + return fmt.Errorf("%s - prepare idempotency: %w", location, err) + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return fmt.Errorf("%s - reserve idempotency: %w", location, err) + } + attempts := unit.AssessmentAttempts() + if !created { + if stored.Fingerprint != request.record.Fingerprint { + return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) + } + outcome, err := attempts.GetCreateOutcome(ctx, request.scope) + if err != nil { + return fmt.Errorf("%s - read immutable create response: %w", location, err) + } + result = outbound.AssessmentAttemptCreateResult{Outcome: outcome, Replayed: true} + return nil + } + if err := attempts.DeleteExpiredOutcome(ctx, request.scope); err != nil { + return fmt.Errorf("%s - remove expired create response: %w", location, err) + } + outcome, err := service.createAttemptInTransaction(ctx, unit, command) + if err != nil { + return err + } + if err := attempts.SaveCreateOutcome(ctx, request.scope, outcome); err != nil { + return fmt.Errorf("%s - store immutable create response: %w", location, err) + } + result = outbound.AssessmentAttemptCreateResult{Outcome: outcome} + return nil + }) + if err != nil { + return outbound.AssessmentAttemptCreateResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func (service *AttemptService) createAttemptInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (outbound.AssessmentAttemptCreateOutcome, error) { + if command.Kind == domain.AssessmentAttemptKindDemoExpress { + return service.createTrainingAttempt(ctx, unit, command) + } + return service.createRealAttempt(ctx, unit, command) +} + +func (service *AttemptService) createRealAttempt( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (outbound.AssessmentAttemptCreateOutcome, error) { + const location = "AttemptService.createRealAttempt" + if err := lockRealAttemptScope(ctx, unit, command); err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - lock C3 and candidate scope: %w", location, err) + } + policyVersion, err := effectiveAttemptPolicy(ctx, unit) + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return assessmentConflictOutcome(), nil + } + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read effective product policy after scope lock: %w", location, err) + } + policy := policyVersion.Policy().Assessment + if policy.Attempt == nil { + return assessmentConflictOutcome(), nil + } + if policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic { + return assessmentConflictOutcome(), nil + } + selection, available, err := resolveRealAttemptSelection(ctx, unit, command, policyVersion) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - resolve current bank selection: %w", location, err) + } + if !available { + return assessmentConflictOutcome(), nil + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read database time after locks: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + if err := validateRealAttemptAvailability(ctx, unit, command, policy, databaseTime); err != nil { + if selectionIsUnavailable(err) || errors.Is(err, outbound.ErrAssessmentAttemptConflict) { + return assessmentConflictOutcome(), nil + } + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - validate current availability: %w", location, err) + } + return service.persistRealAttempt(ctx, unit, command, policyVersion, policy, databaseTime, selection) +} + +func resolveRealAttemptSelection( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, + policyVersion domain.PolicyVersion, +) (outbound.AssessmentBankSelection, bool, error) { + if _, err := validateCandidateAssessmentSelection(ctx, unit, command); err != nil { + return outbound.AssessmentBankSelection{}, false, fmt.Errorf("validate candidate selection: %w", err) + } + active, _, err := activeRealAttemptBlocksCreation(ctx, unit, command) + if err != nil { + return outbound.AssessmentBankSelection{}, false, fmt.Errorf("check active attempt: %w", err) + } + if active { + return outbound.AssessmentBankSelection{}, false, nil + } + selection, err := unit.AssessmentBank().ResolveCurrentSelection( + ctx, *command.Specialization, *command.TargetGrade, command.TaskLanguage, + ) + if err != nil { + if selectionIsUnavailable(err) { + return outbound.AssessmentBankSelection{}, false, nil + } + return outbound.AssessmentBankSelection{}, false, err + } + if selection.ProductPolicyVersionID != policyVersion.ID() || selection.ProductPolicyVersion != policyVersion.Version() { + return outbound.AssessmentBankSelection{}, false, nil + } + return selection, true, nil +} + +func lockRealAttemptScope(ctx context.Context, unit outbound.UnitOfWork, command CreateAttemptCommand) error { + const location = "AttemptService.lockRealAttemptScope" + if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil { + if errors.Is(err, outbound.ErrConsentNotFound) { + return fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptConsentRequired) + } + return fmt.Errorf("%s - lock current C3 consent: %w", location, err) + } + if err := unit.AssessmentAttempts().LockScope(ctx, command.ActorID, command.Specialization); err != nil { + return fmt.Errorf("%s - lock candidate quota and track: %w", location, err) + } + return nil +} + +func activeRealAttemptBlocksCreation( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (bool, time.Time, error) { + const location = "AttemptService.activeRealAttemptBlocksCreation" + repository := unit.AssessmentAttempts() + active, found, err := repository.GetActiveForSpecialization(ctx, command.ActorID, *command.Specialization) + if err != nil { + return false, time.Time{}, err + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return false, time.Time{}, fmt.Errorf("%s - read database time after active row lock: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + if !found { + return false, databaseTime, nil + } + if active.ExpiresAt().After(databaseTime) { + return true, databaseTime, nil + } + if _, _, err := repository.StartOrResumeSession(ctx, command.ActorID, active.ID(), active.Version(), active.ExpiresAt()); err != nil { + return false, time.Time{}, fmt.Errorf("%s - expire due active attempt: %w", location, err) + } + _, found, err = repository.GetActiveForSpecialization(ctx, command.ActorID, *command.Specialization) + if err != nil { + return false, time.Time{}, err + } + return found, databaseTime, nil +} + +func validateRealAttemptAvailability( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, + policy domain.AssessmentPolicy, + now time.Time, +) error { + if _, err := validateCurrentAssessmentSelection(ctx, unit, command); err != nil { + return err + } + if command.Kind == domain.AssessmentAttemptKindRoot { + return checkRootAttemptAvailability(ctx, unit, command, policy, now) + } + return nil +} + +func (service *AttemptService) persistRealAttempt( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, + policyVersion domain.PolicyVersion, + policy domain.AssessmentPolicy, + databaseTime time.Time, + selection outbound.AssessmentBankSelection, +) (outbound.AssessmentAttemptCreateOutcome, error) { + const location = "AttemptService.persistRealAttempt" + itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems + items, err := generatedAssessmentItems(selection.Families, itemCount) + if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) { + return assessmentConflictOutcome(), nil + } + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - generate frozen items: %w", location, err) + } + chain, err := loadCorrectionChain(ctx, unit.AssessmentAttempts(), command) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read correction chain: %w", location, err) + } + attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ + UserID: command.ActorID, Kind: command.Kind, BankCategory: selection.Opening.Category, + Specialization: command.Specialization, TargetGrade: command.TargetGrade, TaskLanguage: command.TaskLanguage, + Chain: chain, Versions: realAttemptVersions(policyVersion, selection), Policy: policyVersion, + CreatedAt: databaseTime, Items: items, + }) + if err != nil { + if errors.Is(err, domain.ErrInvalidAssessmentAttempt) { + return outbound.AssessmentAttemptCreateOutcome{}, attemptFieldError("/target_grade", "does not continue the requested assessment track") + } + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - construct attempt: %w", location, err) + } + if err := unit.AssessmentAttempts().Create(ctx, attempt); err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - persist attempt and frozen items: %w", location, err) + } + return outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: attempt.PublicSnapshot()}, nil +} + +func loadCorrectionChain( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + command CreateAttemptCommand, +) ([]domain.AssessmentAttempt, error) { + if command.Kind != domain.AssessmentAttemptKindCorrective { + return nil, nil + } + chain, err := repository.ListCorrectionChain(ctx, command.ActorID, *command.Specialization, command.RootAttemptID) + if err != nil { + return nil, err + } + if len(chain) == 0 { + return nil, attemptFieldError("/root_attempt_id", "must identify an eligible attempt chain") + } + return chain, nil +} + +func selectionIsUnavailable(err error) bool { + return errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) || errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous) +} + +func (service *AttemptService) createTrainingAttempt( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (outbound.AssessmentAttemptCreateOutcome, error) { + const location = "AttemptService.createTrainingAttempt" + if err := unit.AssessmentAttempts().LockScope(ctx, command.ActorID, nil); err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - lock candidate training scope: %w", location, err) + } + policyVersion, err := effectiveAttemptPolicy(ctx, unit) + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return assessmentConflictOutcome(), nil + } + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read effective product policy after scope lock: %w", location, err) + } + training := policyVersion.Policy().Assessment.Training + if training == nil { + return assessmentConflictOutcome(), nil + } + selection, available, err := resolveTrainingAttemptSelection(ctx, unit, command.ActorID, policyVersion, training) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - resolve reviewed training bank: %w", location, err) + } + if !available { + return assessmentConflictOutcome(), nil + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - read database time after locks: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + items, err := generatedAssessmentItems(selection.Families, training.DemoExpressItemCount) + if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) { + return assessmentConflictOutcome(), nil + } + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - generate frozen training items: %w", location, err) + } + attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ + UserID: command.ActorID, Kind: domain.AssessmentAttemptKindDemoExpress, BankCategory: selection.Category, + Versions: trainingAttemptVersions(policyVersion, selection), Policy: policyVersion, CreatedAt: databaseTime, Items: items, + }) + if err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - construct training attempt: %w", location, err) + } + if err := unit.AssessmentAttempts().Create(ctx, attempt); err != nil { + return outbound.AssessmentAttemptCreateOutcome{}, fmt.Errorf("%s - persist training attempt and frozen items: %w", location, err) + } + return outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: attempt.PublicSnapshot()}, nil +} + +func resolveTrainingAttemptSelection( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + policyVersion domain.PolicyVersion, + training *domain.AssessmentTrainingPolicy, +) (outbound.AssessmentTrainingBankSelection, bool, error) { + active, _, err := activeTrainingAttemptBlocksCreation(ctx, unit, userID) + if err != nil { + return outbound.AssessmentTrainingBankSelection{}, false, fmt.Errorf("check active training attempt: %w", err) + } + if active { + return outbound.AssessmentTrainingBankSelection{}, false, nil + } + selection, err := unit.AssessmentBank().ResolveCurrentTrainingSelection(ctx, policyVersion.ID(), policyVersion.Version()) + if err != nil { + if selectionIsUnavailable(err) { + return outbound.AssessmentTrainingBankSelection{}, false, nil + } + return outbound.AssessmentTrainingBankSelection{}, false, err + } + if selection.ProductPolicyVersionID != policyVersion.ID() || selection.ProductPolicyVersion != policyVersion.Version() || + len(selection.Families) < int(training.DemoExpressItemCount) { + return outbound.AssessmentTrainingBankSelection{}, false, nil + } + return selection, true, nil +} + +func activeTrainingAttemptBlocksCreation( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, +) (bool, time.Time, error) { + const location = "AttemptService.activeTrainingAttemptBlocksCreation" + repository := unit.AssessmentAttempts() + active, found, err := repository.GetActiveTraining(ctx, userID) + if err != nil { + return false, time.Time{}, err + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return false, time.Time{}, fmt.Errorf("%s - read database time after active row lock: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + if !found { + return false, databaseTime, nil + } + if active.ExpiresAt().After(databaseTime) { + return true, databaseTime, nil + } + if _, _, err := repository.StartOrResumeSession(ctx, userID, active.ID(), active.Version(), databaseTime); err != nil { + return false, time.Time{}, fmt.Errorf("%s - expire due attempt: %w", location, err) + } + _, found, err = repository.GetActiveTraining(ctx, userID) + if err != nil { + return false, time.Time{}, err + } + return found, databaseTime, nil +} + +// GetMyAttempt reads only the owner's current public projection. It never +// starts a session or commits an expiry transition. +func (service *AttemptService) GetMyAttempt( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttemptPublicSnapshot, error) { + const location = "AttemptService.GetMyAttempt" + if userID == uuid.Nil || attemptID.IsZero() { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden) + } + var result domain.AssessmentAttemptPublicSnapshot + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil { + return err + } + attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound) + } + if err != nil { + return fmt.Errorf("%s - read owner-scoped attempt: %w", location, err) + } + result = attempt.PublicSnapshot() + return nil + }) + if err != nil { + return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +type StartAttemptSessionCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + ExpectedVersion int64 + IdempotencyKey string +} + +type canonicalAttemptSessionBody struct { + AttemptID string `json:"attempt_id"` + ExpectedVersion int64 `json:"expected_version"` +} + +// StartSession returns the immutable response captured for this session key. +func (service *AttemptService) StartSession( + ctx context.Context, + command StartAttemptSessionCommand, +) (outbound.AssessmentAttemptSessionResult, error) { + const location = "AttemptService.StartSession" + if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - candidate, attempt, and expected version are required: %w", location, ErrInvalidAttemptRequest) + } + body, err := json.Marshal(canonicalAttemptSessionBody{AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion}) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - encode request fingerprint: %w", location, ErrInvalidAttemptRequest) + } + keyTime, err := assessmentIdempotencyTime(service.clock()) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - validate application time: %w", location, err) + } + var result outbound.AssessmentAttemptSessionResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var transactionErr error + result, transactionErr = service.startSessionInTransaction(ctx, unit, command, body, keyTime) + return transactionErr + }) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func (service *AttemptService) startSessionInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command StartAttemptSessionCommand, + body []byte, + keyTime time.Time, +) (outbound.AssessmentAttemptSessionResult, error) { + const location = "AttemptService.startSessionInTransaction" + if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { + return outbound.AssessmentAttemptSessionResult{}, err + } + request, err := service.prepareAttemptIdempotency(startSessionOperation, command.IdempotencyKey, command.ActorID, body, keyTime) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err) + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - reserve idempotency: %w", location, err) + } + if !created { + return replaySessionOutcome(ctx, unit.AssessmentAttempts(), request, stored) + } + return service.startNewSession(ctx, unit, command, request) +} + +func replaySessionOutcome( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + request attemptIdempotencyRequest, + stored outbound.IdempotencyRecord, +) (outbound.AssessmentAttemptSessionResult, error) { + const location = "assessment.replaySessionOutcome" + if stored.Fingerprint != request.record.Fingerprint { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) + } + response, err := repository.GetSessionOutcome(ctx, request.scope) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read immutable session response: %w", location, err) + } + return outbound.AssessmentAttemptSessionResult{Response: response, Replayed: true}, nil +} + +func (service *AttemptService) startNewSession( + ctx context.Context, + unit outbound.UnitOfWork, + command StartAttemptSessionCommand, + request attemptIdempotencyRequest, +) (outbound.AssessmentAttemptSessionResult, error) { + const location = "AttemptService.startNewSession" + repository := unit.AssessmentAttempts() + if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - remove expired session response: %w", location, err) + } + kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound) + } + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) + } + if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - authorize session: %w", location, err) + } + current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound) + } + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if current.Kind() != kind { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read database time after attempt lock: %w", location, err) + } + updated, _, err := repository.StartOrResumeSession(ctx, command.ActorID, command.AttemptID, command.ExpectedVersion, databaseTime) + if errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict) || errors.Is(err, domain.ErrAssessmentAttemptVersionConflict) { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict) + } + if err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - start or resume session: %w", location, err) + } + response := updated.PublicSnapshot() + if err := repository.SaveSessionOutcome(ctx, request.scope, response); err != nil { + return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - store immutable session response: %w", location, err) + } + return outbound.AssessmentAttemptSessionResult{Response: response}, nil +} + +func lockSessionConsent( + ctx context.Context, + unit outbound.UnitOfWork, + actorID uuid.UUID, + kind domain.AssessmentAttemptKind, +) error { + const location = "assessment.lockSessionConsent" + if kind == domain.AssessmentAttemptKindDemoExpress { + return nil + } + if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, actorID, domain.ConsentPurposeAutoCategorization); err != nil { + if errors.Is(err, outbound.ErrConsentNotFound) { + return fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptConsentRequired) + } + return fmt.Errorf("%s - lock current C3 consent: %w", location, err) + } + return nil +} + +type attemptIdempotencyRequest struct { + scope outbound.AssessmentAttemptIdempotencyScope + record outbound.IdempotencyRecord +} + +func (service *AttemptService) prepareAttemptIdempotency( + operation string, + key string, + actorID uuid.UUID, + body []byte, + now time.Time, +) (attemptIdempotencyRequest, error) { + if !validAttemptIdempotencyKey(key) { + return attemptIdempotencyRequest{}, ErrInvalidAttemptKey + } + if len(body) == 0 || len(body) > maxAttemptCanonicalBodyBytes { + return attemptIdempotencyRequest{}, ErrInvalidAttemptRequest + } + expiresAt := now.Add(outbound.IdempotencyRetention) + if expiresAt.Year() > 9999 || !expiresAt.After(now) { + return attemptIdempotencyRequest{}, ErrInvalidAttemptRequest + } + scopeBytes := service.keyring.IdempotencyScope(operation, key, actorID.String()) + fingerprint := service.keyring.Fingerprint(body) + scope := outbound.AssessmentAttemptIdempotencyScope(scopeBytes) + record := outbound.IdempotencyRecord{ + Scope: scopeBytes, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt, + } + return attemptIdempotencyRequest{scope: scope, record: record}, nil +} + +func canonicalizeAttemptCreateBody(command CreateAttemptCommand) ([]byte, error) { + if command.ActorID == uuid.Nil { + return nil, ErrAttemptForbidden + } + body := canonicalAttemptCreateBody{Kind: command.Kind} + switch command.Kind { + case domain.AssessmentAttemptKindRoot: + if !validRealCreateTrack(command) || !command.RootAttemptID.IsZero() { + return nil, ErrInvalidAttemptRequest + } + body.Specialization, body.TargetGrade, body.TaskLanguage = command.Specialization, command.TargetGrade, command.TaskLanguage + case domain.AssessmentAttemptKindCorrective: + if !validRealCreateTrack(command) || command.RootAttemptID.IsZero() { + return nil, ErrInvalidAttemptRequest + } + body.Specialization, body.TargetGrade, body.TaskLanguage = command.Specialization, command.TargetGrade, command.TaskLanguage + rootID := command.RootAttemptID.String() + body.RootAttemptID = rootID + case domain.AssessmentAttemptKindDemoExpress: + if command.Specialization != nil || command.TargetGrade != nil || command.TaskLanguage != nil || !command.RootAttemptID.IsZero() { + return nil, ErrInvalidAttemptRequest + } + default: + return nil, ErrInvalidAttemptRequest + } + encoded, err := json.Marshal(body) + if err != nil || len(encoded) > maxAttemptCanonicalBodyBytes { + return nil, ErrInvalidAttemptRequest + } + return encoded, nil +} + +func validRealCreateTrack(command CreateAttemptCommand) bool { + return command.Specialization != nil && command.Specialization.IsKnown() && + command.TargetGrade != nil && command.TargetGrade.IsKnown() && + (command.TaskLanguage == nil || command.TaskLanguage.IsKnown()) +} + +func validAttemptIdempotencyKey(value string) bool { + if len(value) == 0 || len(value) > maxAttemptIdempotencyKeyBytes { + return false + } + for index := range len(value) { + character := value[index] + if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || + character >= '0' && character <= '9' || character == '.' || character == '_' || character == ':' || character == '-' { + continue + } + return false + } + return true +} + +func assessmentIdempotencyTime(value time.Time) (time.Time, error) { + now := value.UTC().Truncate(time.Microsecond) + if now.IsZero() || now.Year() < 1 || now.Year() > 9999 { + return time.Time{}, ErrInvalidAttemptRequest + } + return now, nil +} + +func requireAttemptCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error { + if userID == uuid.Nil { + return fmt.Errorf("%s - candidate ID is required: %w", location, ErrAttemptForbidden) + } + user, err := unit.Users().GetByID(ctx, userID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - candidate account is missing: %w", location, ErrAttemptForbidden) + } + return fmt.Errorf("%s - read candidate account: %w", location, err) + } + if !user.EmailVerified() { + return fmt.Errorf("%s - require confirmed email: %w", location, ErrAttemptEmailNotVerified) + } + if user.Scenario != domain.ScenarioCandidate { + return fmt.Errorf("%s - require candidate scenario: %w", location, ErrAttemptForbidden) + } + return nil +} + +func validateCandidateAssessmentSelection( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (domain.CandidateQuestionnaire, error) { + questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, command.ActorID) + if err != nil { + return domain.CandidateQuestionnaire{}, fmt.Errorf("read candidate questionnaire: %w", err) + } + for _, answer := range questionnaire.Specializations() { + if answer.Specialization != *command.Specialization { + continue + } + if command.TaskLanguage != nil && !slices.Contains(answer.TaskLanguages, *command.TaskLanguage) { + return domain.CandidateQuestionnaire{}, attemptFieldError("/task_language", "must be one of the candidate's selected task languages") + } + return questionnaire, nil + } + return domain.CandidateQuestionnaire{}, attemptFieldError("/specialization", "must be present in the candidate questionnaire") +} + +func validateCurrentAssessmentSelection( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, +) (domain.SpecializationAvailability, error) { + availability, err := unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx) + if err != nil { + return domain.SpecializationAvailability{}, fmt.Errorf("read current specialization catalog: %w", err) + } + for _, current := range availability { + if current.Specialization != *command.Specialization { + continue + } + if !slices.Contains(current.Grades, *command.TargetGrade) { + return domain.SpecializationAvailability{}, attemptFieldError("/target_grade", "is not offered by the current published bank") + } + if command.TaskLanguage == nil && len(current.TaskLanguages) > 0 { + return domain.SpecializationAvailability{}, attemptFieldError("/task_language", "must be selected from the current published bank") + } + if command.TaskLanguage != nil && !slices.Contains(current.TaskLanguages, *command.TaskLanguage) { + return domain.SpecializationAvailability{}, attemptFieldError("/task_language", "is not offered by the current published bank") + } + return current, nil + } + return domain.SpecializationAvailability{}, outbound.ErrAssessmentSelectionUnavailable +} + +func effectiveAttemptPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.PolicyVersion, error) { + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("read database time: %w", err) + } + policy, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime) + if err != nil { + return domain.PolicyVersion{}, err + } + return policy, nil +} + +func checkRootAttemptAvailability( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateAttemptCommand, + policy domain.AssessmentPolicy, + now time.Time, +) error { + const location = "AttemptService.checkRootAttemptAvailability" + if policy.Attempt == nil || command.Specialization == nil || command.TargetGrade == nil { + return fmt.Errorf("%s - explicit policy and track are required: %w", location, outbound.ErrAssessmentAttemptConflict) + } + repository := unit.AssessmentAttempts() + if err := checkLatestRootAvailability(ctx, repository, command, policy, now); err != nil { + return fmt.Errorf("%s - check latest root: %w", location, err) + } + if err := checkSameGradeRootAvailability(ctx, repository, command, policy, now); err != nil { + return fmt.Errorf("%s - check same-grade retry: %w", location, err) + } + return checkRootQuota(ctx, repository, command.ActorID, policy, now) +} + +func checkLatestRootAvailability( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + command CreateAttemptCommand, + policy domain.AssessmentPolicy, + now time.Time, +) error { + const location = "assessment.checkLatestRootAvailability" + latest, found, err := repository.GetLatestRootForSpecialization(ctx, command.ActorID, *command.Specialization, nil) + if err != nil || !found { + return err + } + chain, err := repository.ListCorrectionChain(ctx, command.ActorID, *command.Specialization, latest.ID()) + if err != nil { + return err + } + if len(chain) == 0 { + return fmt.Errorf("%s - root chain is missing its root: %w", location, domain.ErrInvalidAssessmentAttempt) + } + last := chain[len(chain)-1] + platformFailure, err := attemptHasPlatformFailure(ctx, repository, last) + if err != nil { + return fmt.Errorf("%s - inspect latest attempt result: %w", location, err) + } + if platformFailure { + return nil + } + if hasOpenCorrectionWindow(chain, now) { + return fmt.Errorf("%s - a correction chain remains open: %w", location, outbound.ErrAssessmentAttemptConflict) + } + if isPromotionTooSoon(last, *command.TargetGrade, policy.PromotionMinInterval.Duration(), now) { + return fmt.Errorf("%s - promotion interval has not elapsed: %w", location, outbound.ErrAssessmentAttemptConflict) + } + return nil +} + +func attemptHasPlatformFailure( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + attempt domain.AssessmentAttempt, +) (bool, error) { + if attempt.State() == domain.AssessmentAttemptStateInsufficientBank { + return true, nil + } + if attempt.State() != domain.AssessmentAttemptStateCompleted { + return false, nil + } + result, err := repository.GetResult(ctx, attempt.Snapshot().UserID, attempt.ID()) + if err != nil { + return false, err + } + return isPlatformAttemptFailure(result.NotDeterminedReason), nil +} + +func hasOpenCorrectionWindow(chain []domain.AssessmentAttempt, now time.Time) bool { + return eligibleCorrectionWindow(chain[len(chain)-1]) && now.Before(chain[0].ChainDeadline()) +} + +func isPromotionTooSoon(last domain.AssessmentAttempt, target domain.GradeCode, interval time.Duration, now time.Time) bool { + current := last.Snapshot().TargetGrade + return current != nil && gradeRank(target) > gradeRank(*current) && now.Before(last.UpdatedAt().Add(interval)) +} + +func checkSameGradeRootAvailability( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + command CreateAttemptCommand, + policy domain.AssessmentPolicy, + now time.Time, +) error { + const location = "assessment.checkSameGradeRootAvailability" + latest, found, err := repository.GetLatestRootForSpecialization(ctx, command.ActorID, *command.Specialization, command.TargetGrade) + if err != nil || !found { + return err + } + if now.Before(latest.UpdatedAt().Add(policy.SameGradeRetryAfter.Duration())) { + return fmt.Errorf("%s - same-grade retry interval has not elapsed: %w", location, outbound.ErrAssessmentAttemptConflict) + } + return nil +} + +func checkRootQuota( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + userID uuid.UUID, + policy domain.AssessmentPolicy, + now time.Time, +) error { + const location = "assessment.checkRootQuota" + since := now.Add(-policy.AttemptWindow.Duration()) + count, err := repository.CountRootAttemptsSince(ctx, userID, nil, since) + if err != nil { + return fmt.Errorf("%s - count global root quota: %w", location, err) + } + if count >= policy.MaxAttemptsPerWindow { + return fmt.Errorf("%s - global root quota is exhausted: %w", location, outbound.ErrAssessmentAttemptConflict) + } + return nil +} + +func eligibleCorrectionWindow(attempt domain.AssessmentAttempt) bool { + snapshot := attempt.Snapshot() + if !snapshot.ChainDeadline.After(snapshot.CreatedAt) { + return false + } + switch snapshot.State { + case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending, + domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize, + domain.AssessmentAttemptStateInsufficientBank: + return false + case domain.AssessmentAttemptStateExpired: + return snapshot.Outcome == "" + case domain.AssessmentAttemptStateCompleted: + return snapshot.Outcome == domain.AssessmentAttemptOutcomeNotConfirmed || + snapshot.Outcome == domain.AssessmentAttemptOutcomeNotDetermined + default: + return false + } +} + +func gradeRank(grade domain.GradeCode) int { + switch grade { + case domain.GradeIntern: + return 0 + case domain.GradeJunior: + return 1 + case domain.GradeMiddle: + return 2 + case domain.GradeSenior: + return 3 + default: + return -1 + } +} + +func generatedAssessmentItems( + families []domain.AssessmentFamily, + count int32, +) ([]domain.AssessmentAttemptItemInput, error) { + if count < 1 || count > attemptVariantLimit || len(families) < int(count) { + return nil, outbound.ErrAssessmentSelectionUnavailable + } + selected := slices.Clone(families) + for index := len(selected) - 1; index > 0; index-- { + bound := big.NewInt(int64(index + 1)) + choice, err := cryptorand.Int(cryptorand.Reader, bound) + if err != nil { + return nil, fmt.Errorf("generatedAssessmentItems - choose family: %w", err) + } + selectedIndex := int(choice.Int64()) + selected[index], selected[selectedIndex] = selected[selectedIndex], selected[index] + } + items := make([]domain.AssessmentAttemptItemInput, 0, count) + for _, family := range selected[:int(count)] { + var seedBytes [8]byte + if _, err := cryptorand.Read(seedBytes[:]); err != nil { + return nil, fmt.Errorf("generatedAssessmentItems - generate variant seed: %w", err) + } + variant, err := family.NewVariant(domain.VariantSeed(binary.LittleEndian.Uint64(seedBytes[:]))) + if err != nil { + return nil, fmt.Errorf("generatedAssessmentItems - generate frozen variant: %w", err) + } + items = append(items, domain.AssessmentAttemptItemInput{Variant: variant}) + } + return items, nil +} + +func realAttemptVersions( + policy domain.PolicyVersion, + selection outbound.AssessmentBankSelection, +) domain.AssessmentAttemptVersions { + return domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + GradingPolicyVersionID: selection.Opening.PolicyVersionID, OpeningID: selection.Opening.ID, + OpeningManifestHash: selection.ManifestSHA, + BankVersion: "bank." + hex.EncodeToString(selection.ManifestSHA[:12]), + AlgorithmVersion: attemptAlgorithmVersion, + } +} + +func trainingAttemptVersions( + policy domain.PolicyVersion, + selection outbound.AssessmentTrainingBankSelection, +) domain.AssessmentAttemptVersions { + return domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + TrainingBindingID: selection.BindingID, TrainingManifestHash: selection.ManifestSHA, + BankVersion: "training." + hex.EncodeToString(selection.ManifestSHA[:12]), + AlgorithmVersion: attemptAlgorithmVersion, + } +} + +func assessmentConflictOutcome() outbound.AssessmentAttemptCreateOutcome { + return outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"} +} + +func attemptFieldError(pointer, reason string) error { + return &AttemptFieldError{Pointer: pointer, Reason: reason} +} + +func storeAttemptCommandProblem( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + operation string, + statusCode int16, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "assessment.storeAttemptCommandProblem" + problemCode, allowed := assessmentAttemptProblemCode(statusCode) + if !allowed { + return fmt.Errorf("%s - problem status is not allowlisted", location) + } + outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: statusCode, ProblemCode: problemCode} + switch operation { + case "answer": + if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store answer problem outcome: %w", location, err) + } + case "finalize": + if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store finalize problem outcome: %w", location, err) + } + default: + return fmt.Errorf("%s - operation is not allowlisted", location) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} + return nil +} + +func assessmentAttemptProblemCode(statusCode int16) (string, bool) { + switch statusCode { + case 404: + return "not_found", true + case 409: + return "state_conflict", true + default: + return "", false + } +} + +func storeFinalizePendingItems( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + itemIDs []uuid.UUID, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "assessment.storeFinalizePendingItems" + if len(itemIDs) == 0 || len(itemIDs) > 220 { + return fmt.Errorf("%s - pending item list is outside its bound", location) + } + outcome := outbound.AssessmentAttemptCommandOutcome{ + StatusCode: 409, ProblemCode: "state_conflict", PendingItemIDs: append([]uuid.UUID{}, itemIDs...), + } + if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store finalize conflict: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} + return nil +} diff --git a/backend/internal/usecase/assessment/availability.go b/backend/internal/usecase/assessment/availability.go new file mode 100644 index 0000000..9687c5a --- /dev/null +++ b/backend/internal/usecase/assessment/availability.go @@ -0,0 +1,517 @@ +package assessment + +import ( + "context" + "errors" + "fmt" + "slices" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ErrAssessmentAvailabilityNotImplemented = errors.New("assessment availability is not implemented for the effective policy") + +type AvailabilityStatus string + +const ( + AvailabilityStatusAvailable AvailabilityStatus = "available" + AvailabilityStatusActiveAttempt AvailabilityStatus = "active_attempt" + AvailabilityStatusCooldown AvailabilityStatus = "cooldown" + AvailabilityStatusInsufficientBank AvailabilityStatus = "insufficient_bank" +) + +type AssessmentAvailability struct { + Specializations []SpecializationAvailability +} + +type SpecializationAvailability struct { + Specialization domain.SpecializationCode + ConfirmedGrade *domain.GradeCode + ActiveAttemptID *domain.AssessmentAttemptID + Grades []GradeAvailability +} + +type GradeAvailability struct { + Grade domain.GradeCode + Status AvailabilityStatus + Mode *domain.AssessmentRealMode + AvailableAt *time.Time + TimeLimitSeconds *int32 + MaxSessions *int32 + MaxItems *int32 + PracticeRequired *bool +} + +// GetMyAssessmentAvailability is a read-only candidate preflight. All +// repositories run under one repeatable-read snapshot so policy, bank, +// questionnaire, attempts, and disclosed families agree on one database view. +func (service *AttemptService) GetMyAssessmentAvailability( + ctx context.Context, + userID uuid.UUID, +) (AssessmentAvailability, error) { + const location = "AttemptService.GetMyAssessmentAvailability" + var availability AssessmentAvailability + err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil { + return err + } + now, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read snapshot database time: %w", location, err) + } + now = now.UTC().Truncate(time.Microsecond) + assessmentPolicy, err := readAvailabilityPolicy(ctx, unit, now) + if err != nil { + return fmt.Errorf("%s - read effective assessment policy: %w", location, err) + } + questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, userID) + if err != nil { + return fmt.Errorf("%s - read candidate questionnaire: %w", location, err) + } + availability, err = buildAssessmentAvailability(ctx, unit, userID, now, assessmentPolicy, questionnaire) + if err != nil { + return fmt.Errorf("%s - build assessment availability: %w", location, err) + } + return nil + }) + if err != nil { + return AssessmentAvailability{}, fmt.Errorf("%s - read snapshot: %w", location, err) + } + return availability, nil +} + +func readAvailabilityPolicy( + ctx context.Context, + unit outbound.UnitOfWork, + now time.Time, +) (domain.AssessmentPolicy, error) { + const location = "assessment.readAvailabilityPolicy" + version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now) + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return domain.AssessmentPolicy{}, fmt.Errorf("%s - no effective assessment policy: %w", location, ErrAssessmentAvailabilityNotImplemented) + } + if err != nil { + return domain.AssessmentPolicy{}, err + } + policy := version.Policy().Assessment + if policy.Attempt == nil || policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic { + return domain.AssessmentPolicy{}, fmt.Errorf("%s - effective real assessment mode is not implemented: %w", location, ErrAssessmentAvailabilityNotImplemented) + } + return policy, nil +} + +type assessmentAvailabilityReads struct { + selections []outbound.AssessmentAvailabilitySelection + active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary + rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary + quota outbound.AssessmentRootQuotaSnapshot + seen map[domain.AssessmentFamilyKey]struct{} +} + +func buildAssessmentAvailability( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + now time.Time, + policy domain.AssessmentPolicy, + questionnaire domain.CandidateQuestionnaire, +) (AssessmentAvailability, error) { + reads, err := readAssessmentAvailability(ctx, unit, userID, now, policy, questionnaire) + if err != nil { + return AssessmentAvailability{}, err + } + seconds, err := assessmentLimitSeconds(policy.Attempt.Lifetime.Duration()) + if err != nil { + return AssessmentAvailability{}, err + } + itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems + result := AssessmentAvailability{Specializations: make([]SpecializationAvailability, 0, len(questionnaire.Specializations()))} + for _, answer := range questionnaire.Specializations() { + result.Specializations = append(result.Specializations, buildSpecializationAvailability( + answer, reads, policy, now, seconds, itemCount, + )) + } + return result, nil +} + +func assessmentLimitSeconds(duration time.Duration) (int32, error) { + seconds := duration / time.Second + if seconds <= 0 || seconds > time.Duration(1<<31-1) { + return 0, fmt.Errorf("assessment availability limit exceeds supported seconds: %w", domain.ErrInvalidPolicy) + } + return int32(seconds), nil +} + +func readAssessmentAvailability( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + now time.Time, + policy domain.AssessmentPolicy, + questionnaire domain.CandidateQuestionnaire, +) (assessmentAvailabilityReads, error) { + const location = "assessment.readAssessmentAvailability" + selections, err := unit.AssessmentBank().ListCurrentAssessmentAvailabilitySelections(ctx, now) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read bank: %w", location, err) + } + reads := assessmentAvailabilityReads{selections: selections} + reads.active, err = readActiveAvailabilityAttempts(ctx, unit, userID, now, questionnaire) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err) + } + window := policy.AttemptWindow.Duration() + reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot( + ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow, + ) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root quota: %w", location, err) + } + reads.rootHistory, err = readAvailabilityRootHistory(ctx, unit, userID, now, policy, questionnaire) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root retry history: %w", location, err) + } + keys, err := unit.AssessmentAttempts().ListDisclosedFamilyKeys(ctx, userID, now.Add(-365*24*time.Hour)) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read disclosed families: %w", location, err) + } + reads.seen = make(map[domain.AssessmentFamilyKey]struct{}, len(keys)) + for _, key := range keys { + reads.seen[key] = struct{}{} + } + return reads, nil +} + +func readActiveAvailabilityAttempts( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + now time.Time, + questionnaire domain.CandidateQuestionnaire, +) (map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary, error) { + activeBySpecialization := make(map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary) + for _, answer := range questionnaire.Specializations() { + active, found, err := unit.AssessmentAttempts().GetAvailabilityActiveAttempt(ctx, userID, answer.Specialization) + if err != nil { + return nil, err + } + if found && active.ExpiresAt.After(now) { + activeBySpecialization[answer.Specialization] = active + } + } + return activeBySpecialization, nil +} + +func readAvailabilityRootHistory( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + now time.Time, + policy domain.AssessmentPolicy, + questionnaire domain.CandidateQuestionnaire, +) (map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary, error) { + horizon := max(policy.AttemptWindow.Duration(), policy.SameGradeRetryAfter.Duration(), + policy.PromotionMinInterval.Duration()) + policy.Attempt.ChainDeadline.Duration() + history := make(map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary) + for _, answer := range questionnaire.Specializations() { + rows, err := unit.AssessmentAttempts().ListAvailabilityRootSummaries( + ctx, userID, answer.Specialization, now.Add(-horizon), + ) + if err != nil { + return nil, err + } + history[answer.Specialization] = rows + } + return history, nil +} + +func buildSpecializationAvailability( + answer domain.QuestionnaireSpecialization, + reads assessmentAvailabilityReads, + policy domain.AssessmentPolicy, + now time.Time, + seconds, itemCount int32, +) SpecializationAvailability { + active, hasActive := reads.active[answer.Specialization] + result := SpecializationAvailability{ + Specialization: answer.Specialization, + Grades: make([]GradeAvailability, 0, len(availabilityGrades)), + } + if hasActive { + id := active.ID + result.ActiveAttemptID = &id + } + for _, grade := range availabilityGrades { + result.Grades = append(result.Grades, buildGradeAvailability( + answer, grade, reads, policy, now, seconds, itemCount, hasActive, + )) + } + return result +} + +func buildGradeAvailability( + answer domain.QuestionnaireSpecialization, + grade domain.GradeCode, + reads assessmentAvailabilityReads, + policy domain.AssessmentPolicy, + now time.Time, + seconds, itemCount int32, + hasActive bool, +) GradeAvailability { + result := GradeAvailability{Grade: grade} + if hasActive { + result.Status = AvailabilityStatusActiveAttempt + } else if !hasSufficientUnseenBank(answer, grade, reads.selections, reads.seen, itemCount) { + result.Status = AvailabilityStatusInsufficientBank + return result + } else if availableAt := rootCooldownUntil(reads.rootHistory[answer.Specialization], grade, policy, reads.quota, now); availableAt != nil { + result.Status = AvailabilityStatusCooldown + result.AvailableAt = availableAt + } else { + result.Status = AvailabilityStatusAvailable + } + mode := policy.Attempt.RealMode + result.setLimits(mode, seconds, policy.Attempt.MaxSessions, itemCount, false) + return result +} + +var availabilityGrades = [...]domain.GradeCode{ + domain.GradeIntern, domain.GradeJunior, domain.GradeMiddle, domain.GradeSenior, +} + +func (grade *GradeAvailability) setLimits( + mode domain.AssessmentRealMode, + seconds, maxSessions, maxItems int32, + practiceRequired bool, +) { + grade.Mode = &mode + grade.TimeLimitSeconds = &seconds + grade.MaxSessions = &maxSessions + grade.MaxItems = &maxItems + grade.PracticeRequired = &practiceRequired +} + +func hasSufficientUnseenBank( + answer domain.QuestionnaireSpecialization, + grade domain.GradeCode, + selections []outbound.AssessmentAvailabilitySelection, + seen map[domain.AssessmentFamilyKey]struct{}, + minimum int32, +) bool { + catalogLanguages := availabilityLanguages(answer.Specialization, selections) + if len(catalogLanguages) > 0 && len(answer.TaskLanguages) == 0 { + return false + } + languages := answer.TaskLanguages + if len(catalogLanguages) == 0 { + if len(languages) > 0 { + return false + } + languages = []domain.TaskLanguageCode{""} + } + for _, language := range languages { + if len(catalogLanguages) > 0 && !slices.Contains(catalogLanguages, language) { + continue + } + selection, found := uniqueAvailabilitySelection(selections, answer.Specialization, grade, language) + if !found { + continue + } + unseen := int32(0) + for _, key := range selection.FamilyKeys { + if _, exists := seen[key]; !exists { + unseen++ + } + } + if unseen >= minimum { + return true + } + } + return false +} + +func availabilityLanguages( + specialization domain.SpecializationCode, + selections []outbound.AssessmentAvailabilitySelection, +) []domain.TaskLanguageCode { + var languages []domain.TaskLanguageCode + for _, selection := range selections { + if selection.Specialization != specialization { + continue + } + for _, language := range selection.TaskLanguages { + if !slices.Contains(languages, language) { + languages = append(languages, language) + } + } + } + return languages +} + +func uniqueAvailabilitySelection( + selections []outbound.AssessmentAvailabilitySelection, + specialization domain.SpecializationCode, + grade domain.GradeCode, + language domain.TaskLanguageCode, +) (outbound.AssessmentAvailabilitySelection, bool) { + var match outbound.AssessmentAvailabilitySelection + count := 0 + for _, selection := range selections { + if selection.Specialization != specialization || selection.Grade != grade { + continue + } + if language == "" && len(selection.TaskLanguages) == 0 || slices.Contains(selection.TaskLanguages, language) { + match = selection + count++ + } + } + return match, count == 1 +} + +func rootCooldownUntil( + roots []outbound.AssessmentRootAvailabilitySummary, + target domain.GradeCode, + policy domain.AssessmentPolicy, + quota outbound.AssessmentRootQuotaSnapshot, + now time.Time, +) *time.Time { + latest, latestSameGrade := latestAvailabilityRoots(roots, target) + var blockedUntil time.Time + blockedUntil = sameGradeAvailabilityCooldown(blockedUntil, latestSameGrade, policy, now) + blockedUntil = latestRootAvailabilityCooldown(blockedUntil, latest, target, policy, now) + if quota.Count >= policy.MaxAttemptsPerWindow && quota.AvailableAt != nil { + blockedUntil = laterAvailability(blockedUntil, *quota.AvailableAt, now) + } + if blockedUntil.IsZero() { + return nil + } + availableAt := blockedUntil.UTC().Truncate(time.Microsecond) + return &availableAt +} + +func latestAvailabilityRoots( + roots []outbound.AssessmentRootAvailabilitySummary, + target domain.GradeCode, +) (*outbound.AssessmentRootAvailabilitySummary, *outbound.AssessmentRootAvailabilitySummary) { + var latest *outbound.AssessmentRootAvailabilitySummary + var latestSameGrade *outbound.AssessmentRootAvailabilitySummary + for index := range roots { + root := &roots[index] + if latest == nil || root.RootCreatedAt.After(latest.RootCreatedAt) { + latest = root + } + if root.RootTargetGrade == target && + (latestSameGrade == nil || root.RootCreatedAt.After(latestSameGrade.RootCreatedAt)) { + latestSameGrade = root + } + } + return latest, latestSameGrade +} + +func sameGradeAvailabilityCooldown( + blockedUntil time.Time, + latestSameGrade *outbound.AssessmentRootAvailabilitySummary, + policy domain.AssessmentPolicy, + now time.Time, +) time.Time { + if latestSameGrade != nil { + updatedAt := effectiveAvailabilityUpdatedAt(latestSameGrade.RootState, latestSameGrade.RootUpdatedAt, latestSameGrade.RootExpiresAt, now) + blockedUntil = laterAvailability(blockedUntil, updatedAt.Add(policy.SameGradeRetryAfter.Duration()), now) + } + return blockedUntil +} + +func latestRootAvailabilityCooldown( + blockedUntil time.Time, + latest *outbound.AssessmentRootAvailabilitySummary, + target domain.GradeCode, + policy domain.AssessmentPolicy, + now time.Time, +) time.Time { + if latest != nil { + lastUpdatedAt := effectiveAvailabilityUpdatedAt(latest.LatestState, latest.LatestUpdatedAt, latest.LatestExpiresAt, now) + platformFailure := latest.LatestState == domain.AssessmentAttemptStateInsufficientBank || + isPlatformAttemptFailure(latest.LatestPlatformError) + if !platformFailure && + availabilityCorrectionWindowOpen(latest, now) { + blockedUntil = laterAvailability(blockedUntil, latest.LatestChainDeadline, now) + } + if !platformFailure && gradeRank(target) > gradeRank(latest.LatestTargetGrade) { + blockedUntil = laterAvailability(blockedUntil, lastUpdatedAt.Add(policy.PromotionMinInterval.Duration()), now) + } + } + return blockedUntil +} + +func effectiveAvailabilityUpdatedAt( + state domain.AssessmentAttemptState, + updatedAt, expiresAt, now time.Time, +) time.Time { + if isAssessmentAttemptActiveState(state) && !expiresAt.After(now) { + // A read-only preflight may notice expiry after the deadline. Use the + // attempt's fixed deadline as the transition time so polling cannot + // extend the retry interval. + return expiresAt + } + return updatedAt +} + +func availabilityCorrectionWindowOpen(root *outbound.AssessmentRootAvailabilitySummary, now time.Time) bool { + if !root.LatestChainDeadline.After(root.RootCreatedAt) || !now.Before(root.LatestChainDeadline) { + return false + } + if root.LatestState == domain.AssessmentAttemptStateInsufficientBank || + isPlatformAttemptFailure(root.LatestPlatformError) { + return false + } + switch root.LatestState { + case domain.AssessmentAttemptStateInProgress, + domain.AssessmentAttemptStatePracticePending, + domain.AssessmentAttemptStateAdditionalPracticePending, + domain.AssessmentAttemptStateReadyToFinalize: + // The GET does not write the expiry transition. An expired active + // attempt still holds its correction chain until the immutable chain + // deadline, matching the POST path that records expiry at expires_at. + return !root.LatestExpiresAt.After(now) && root.LatestOutcome == "" + case domain.AssessmentAttemptStateInsufficientBank: + return false + case domain.AssessmentAttemptStateExpired: + return root.LatestOutcome == "" + case domain.AssessmentAttemptStateCompleted: + return root.LatestOutcome == domain.AssessmentAttemptOutcomeNotConfirmed || + root.LatestOutcome == domain.AssessmentAttemptOutcomeNotDetermined + default: + return false + } +} + +func isAssessmentAttemptActiveState(state domain.AssessmentAttemptState) bool { + switch state { + case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending, + domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize: + return true + case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired, + domain.AssessmentAttemptStateInsufficientBank: + return false + default: + return false + } +} + +func isPlatformAttemptFailure(reason string) bool { + return reason == "insufficient_bank" || reason == "sandbox_unavailable" +} + +func laterAvailability(current, candidate, now time.Time) time.Time { + if !candidate.After(now) { + return current + } + if current.IsZero() || candidate.After(current) { + return candidate + } + return current +} diff --git a/backend/internal/usecase/assessment/availability_test.go b/backend/internal/usecase/assessment/availability_test.go new file mode 100644 index 0000000..2901959 --- /dev/null +++ b/backend/internal/usecase/assessment/availability_test.go @@ -0,0 +1,100 @@ +package assessment + +import ( + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestExpiredActiveAttemptCooldownDoesNotMoveWithAvailabilityReads(t *testing.T) { + createdAt := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC) + expiresAt := createdAt.Add(24 * time.Hour) + chainDeadline := createdAt.Add(72 * time.Hour) + root := outbound.AssessmentRootAvailabilitySummary{ + RootTargetGrade: domain.GradeJunior, + RootCreatedAt: createdAt, + RootUpdatedAt: createdAt.Add(12 * time.Hour), + RootExpiresAt: expiresAt, + RootState: domain.AssessmentAttemptStateInProgress, + RootChainDeadline: chainDeadline, + LatestTargetGrade: domain.GradeJunior, + LatestUpdatedAt: createdAt.Add(12 * time.Hour), + LatestExpiresAt: expiresAt, + LatestState: domain.AssessmentAttemptStateInProgress, + LatestChainDeadline: chainDeadline, + } + policy := domain.AssessmentPolicy{SameGradeRetryAfter: 7} + firstReadAt := expiresAt.Add(time.Hour) + secondReadAt := firstReadAt.Add(6 * time.Hour) + want := expiresAt.Add(7 * 24 * time.Hour) + + for _, now := range []time.Time{firstReadAt, secondReadAt} { + got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy, + outbound.AssessmentRootQuotaSnapshot{}, now) + if got == nil || !got.Equal(want) { + t.Fatalf("rootCooldownUntil(%s) = %v, want fixed expiry-based deadline %s", now, got, want) + } + } + if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy, + outbound.AssessmentRootQuotaSnapshot{}, want); got != nil { + t.Fatalf("rootCooldownUntil(after deadline) = %s, want no cooldown", got) + } +} + +func TestExpiredActiveAttemptUsesNaturalExpiryForRetryTimestamp(t *testing.T) { + updatedAt := time.Date(2026, time.January, 2, 10, 0, 0, 0, time.UTC) + expiresAt := updatedAt.Add(-time.Hour) + now := updatedAt.Add(30 * time.Minute) + if got := effectiveAvailabilityUpdatedAt(domain.AssessmentAttemptStateInProgress, updatedAt, expiresAt, now); !got.Equal(expiresAt) { + t.Fatalf("effectiveAvailabilityUpdatedAt() = %s, want original expiry %s", got, expiresAt) + } + root := &outbound.AssessmentRootAvailabilitySummary{ + RootCreatedAt: expiresAt.Add(-24 * time.Hour), + LatestState: domain.AssessmentAttemptStateInProgress, + LatestOutcome: "", + LatestExpiresAt: expiresAt, + LatestChainDeadline: expiresAt.Add(48 * time.Hour), + } + if !availabilityCorrectionWindowOpen(root, now) { + t.Fatal("expired active attempt should hold the correction chain until its fixed deadline") + } + if availabilityCorrectionWindowOpen(root, root.LatestChainDeadline) { + t.Fatal("correction chain should close at its fixed deadline") + } +} + +func TestPlatformFailureDoesNotAddPromotionCooldown(t *testing.T) { + now := time.Date(2026, time.January, 4, 12, 0, 0, 0, time.UTC) + updatedAt := now.Add(-time.Hour) + policy := domain.AssessmentPolicy{PromotionMinInterval: 90} + + tests := []struct { + name string + state domain.AssessmentAttemptState + reason string + }{ + {name: "sandbox failure result", state: domain.AssessmentAttemptStateCompleted, reason: "sandbox_unavailable"}, + {name: "insufficient bank state", state: domain.AssessmentAttemptStateInsufficientBank}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + root := outbound.AssessmentRootAvailabilitySummary{ + RootTargetGrade: domain.GradeJunior, + RootCreatedAt: now.Add(-48 * time.Hour), + RootUpdatedAt: now.Add(-48 * time.Hour), + RootState: domain.AssessmentAttemptStateCompleted, + LatestTargetGrade: domain.GradeMiddle, + LatestUpdatedAt: updatedAt, + LatestExpiresAt: updatedAt.Add(-time.Hour), + LatestState: test.state, + LatestPlatformError: test.reason, + } + if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeSenior, + policy, outbound.AssessmentRootQuotaSnapshot{}, now); got != nil { + t.Fatalf("rootCooldownUntil() = %s, want no platform-failure cooldown", got) + } + }) + } +} diff --git a/backend/internal/usecase/assessment/finalize.go b/backend/internal/usecase/assessment/finalize.go new file mode 100644 index 0000000..ce0af80 --- /dev/null +++ b/backend/internal/usecase/assessment/finalize.go @@ -0,0 +1,404 @@ +package assessment + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const finalizeAttemptOperation = "assessment_attempt.finalize" + +type FinalizeAssessmentAttemptCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + ExpectedVersion int64 + IdempotencyKey string +} + +type canonicalAttemptFinalizeBody struct { + AttemptID string `json:"attempt_id"` + ExpectedVersion int64 `json:"expected_version"` +} + +// AssessmentAttemptResult contains only the candidate-visible result data. +type AssessmentAttemptResult struct { + Attempt domain.AssessmentAttemptPublicSnapshot + Outcome domain.AssessmentAttemptOutcome + NotDeterminedReason string + BasicScore *domain.AssessmentBasicScore + Limitations []string + Summary string + DecidedAt time.Time +} + +// FinalizeAttempt stores a pinned-policy decision and its idempotent response +// in the same transaction as the attempt transition. +func (service *AttemptService) FinalizeAttempt( + ctx context.Context, + command FinalizeAssessmentAttemptCommand, +) (outbound.AssessmentAttemptCommandResult, error) { + const location = "AttemptService.FinalizeAttempt" + if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 { + return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest + } + body, err := json.Marshal(canonicalAttemptFinalizeBody{ + AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion, + }) + if err != nil || len(body) > maxAttemptCanonicalBodyBytes { + return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest + } + keyTime, err := assessmentIdempotencyTime(service.clock()) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err) + } + request, err := service.prepareAttemptIdempotency(finalizeAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err) + } + var result outbound.AssessmentAttemptCommandResult + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { + return err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return fmt.Errorf("%s - reserve idempotency: %w", location, err) + } + repository := unit.AssessmentAttempts() + if !created { + return replayAttemptFinalize(ctx, repository, request, stored, &result) + } + if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil { + return fmt.Errorf("%s - remove expired finalize response: %w", location, err) + } + return service.finalizeNewAttempt(ctx, unit, repository, request.scope, command, &result) + }) + if err != nil { + return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func replayAttemptFinalize( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + request attemptIdempotencyRequest, + stored outbound.IdempotencyRecord, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "assessment.replayAttemptFinalize" + if stored.Fingerprint != request.record.Fingerprint { + return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) + } + outcome, err := repository.GetFinalizeOutcome(ctx, request.scope) + if err != nil { + return fmt.Errorf("%s - read immutable finalize response: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true} + return nil +} + +func (service *AttemptService) finalizeNewAttempt( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command FinalizeAssessmentAttemptCommand, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.finalizeNewAttempt" + current, err := lockAttemptForFinalize(ctx, unit, repository, command) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 404, result) + } + if err != nil { + return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if current.State() != domain.AssessmentAttemptStateCompleted && command.ExpectedVersion != current.Version() { + return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict) + } + if current.State() == domain.AssessmentAttemptStateCompleted { + return storeCompletedFinalize(ctx, repository, scope, command, current, result) + } + return service.finalizeActiveAttempt(ctx, unit, repository, scope, command, current, result) +} + +func lockAttemptForFinalize( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentAttemptRepository, + command FinalizeAssessmentAttemptCommand, +) (domain.AssessmentAttempt, error) { + const location = "AttemptService.lockAttemptForFinalize" + kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) + } + if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err) + } + current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if current.Kind() != kind { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return current, nil +} + +func storeCompletedFinalize( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command FinalizeAssessmentAttemptCommand, + current domain.AssessmentAttempt, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.storeCompletedFinalize" + if _, err := repository.GetResult(ctx, command.ActorID, command.AttemptID); err != nil { + return fmt.Errorf("%s - completed attempt has no immutable result: %w", location, err) + } + outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: current.PublicSnapshot()} + if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store completed finalize response: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} + return nil +} + +func (service *AttemptService) finalizeActiveAttempt( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command FinalizeAssessmentAttemptCommand, + current domain.AssessmentAttempt, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.finalizeActiveAttempt" + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + policyID := current.Snapshot().Versions.ProductPolicyVersionID + policy, err := unit.Policies().GetByID(ctx, policyID) + if err != nil { + return fmt.Errorf("%s - read pinned product policy: %w", location, err) + } + if current.State() == domain.AssessmentAttemptStateInProgress { + expired, changed, expireErr := current.ExpireIfDue(databaseTime) + if expireErr != nil { + return fmt.Errorf("%s - apply due attempt deadline: %w", location, expireErr) + } + if changed { + if err := repository.SaveTransition(ctx, current, expired); err != nil { + return fmt.Errorf("%s - persist due attempt deadline: %w", location, err) + } + return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result) + } + } + if pendingItemIDs := current.PendingItemIDs(); len(pendingItemIDs) > 0 { + return storeFinalizePendingItems(ctx, repository, scope, pendingItemIDs, result) + } + updated, changed, decision, finalizeErr := current.FinalizeDemo( + command.ExpectedVersion, policy.Policy().Assessment, databaseTime, + ) + if finalizeErr != nil { + if errors.Is(finalizeErr, domain.ErrAssessmentAttemptVersionConflict) { + return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict) + } + if errors.Is(finalizeErr, domain.ErrAssessmentAttemptNotActive) { + return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result) + } + return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr) + } + return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result) +} + +func persistFinalizedAttempt( + ctx context.Context, + repository outbound.AssessmentAttemptRepository, + scope outbound.AssessmentAttemptIdempotencyScope, + command FinalizeAssessmentAttemptCommand, + current, updated domain.AssessmentAttempt, + changed bool, + decision domain.AssessmentAttemptDecision, + result *outbound.AssessmentAttemptCommandResult, +) error { + const location = "AttemptService.persistFinalizedAttempt" + if changed { + if err := repository.SaveTransition(ctx, current, updated); err != nil { + return fmt.Errorf("%s - persist final decision: %w", location, err) + } + summary, limitations := assessmentFinalizedResultPresentation(updated.Kind()) + storedResult, err := domain.NewAssessmentAttemptResultSnapshot(updated, decision, summary, limitations) + if err != nil { + return fmt.Errorf("%s - build immutable result snapshot: %w", location, err) + } + if err := repository.SaveResult(ctx, command.ActorID, storedResult); err != nil { + return fmt.Errorf("%s - persist immutable result snapshot: %w", location, err) + } + } + outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()} + if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil { + return fmt.Errorf("%s - store immutable finalize response: %w", location, err) + } + *result = outbound.AssessmentAttemptCommandResult{Outcome: outcome} + return nil +} + +func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) { + if kind == domain.AssessmentAttemptKindDemoExpress { + return "This training run is educational only. It does not assess or confirm a grade.", []string{"demonstration_only"} + } + return "", []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"} +} + +// GetMyResult returns an immutable completed result or a terminal no-result projection. +func (service *AttemptService) GetMyResult( + ctx context.Context, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (AssessmentAttemptResult, error) { + const location = "AttemptService.GetMyResult" + if userID == uuid.Nil || attemptID.IsZero() { + return AssessmentAttemptResult{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden) + } + var result AssessmentAttemptResult + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil { + return err + } + var readErr error + result, readErr = service.readAttemptResult(ctx, unit, userID, attemptID) + return readErr + }) + if err != nil { + return AssessmentAttemptResult{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +func (service *AttemptService) readAttemptResult( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, +) (AssessmentAttemptResult, error) { + const location = "AttemptService.readAttemptResult" + attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound) + } + if err != nil { + return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, err) + } + snapshot := attempt.Snapshot() + if err := validateAttemptResultState(snapshot); err != nil { + return AssessmentAttemptResult{}, fmt.Errorf("%s - validate terminal attempt: %w", location, err) + } + if snapshot.State == domain.AssessmentAttemptStateCompleted { + return readCompletedAttemptResult(ctx, unit, userID, attemptID, attempt) + } + return terminalAttemptResult(attempt) +} + +func validateAttemptResultState(snapshot domain.AssessmentAttemptSnapshot) error { + switch snapshot.State { + case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired, + domain.AssessmentAttemptStateInsufficientBank: + if snapshot.EndedAt.IsZero() { + return domain.ErrInvalidAssessmentAttempt + } + return nil + case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending, + domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize: + return ErrAttemptStateConflict + default: + return domain.ErrInvalidAssessmentAttempt + } +} + +func readCompletedAttemptResult( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + attemptID domain.AssessmentAttemptID, + attempt domain.AssessmentAttempt, +) (AssessmentAttemptResult, error) { + const location = "AttemptService.readCompletedAttemptResult" + stored, err := unit.AssessmentAttempts().GetResult(ctx, userID, attemptID) + if err != nil { + return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err) + } + if !assessmentResultMatchesAttempt(stored, attempt) { + return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return assessmentAttemptResultFromSnapshot(stored), nil +} + +func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) { + snapshot := attempt.Snapshot() + result := AssessmentAttemptResult{Attempt: attempt.PublicSnapshot(), DecidedAt: snapshot.EndedAt} + switch snapshot.Kind { + case domain.AssessmentAttemptKindDemoExpress: + result.Outcome = domain.AssessmentAttemptOutcomeDemonstration + result.Summary = "This training run ended before completion. It does not assess or confirm a grade." + case domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective: + result.Limitations = []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"} + result.Outcome = domain.AssessmentAttemptOutcomeNotDetermined + if snapshot.State == domain.AssessmentAttemptStateExpired { + result.NotDeterminedReason = "expired" + } else { + result.NotDeterminedReason = "insufficient_bank" + } + default: + return AssessmentAttemptResult{}, fmt.Errorf("AttemptService.terminalAttemptResult - attempt kind is unsupported: %w", domain.ErrInvalidAssessmentAttempt) + } + return result, nil +} + +func assessmentResultMatchesAttempt( + result domain.AssessmentAttemptResultSnapshot, + attempt domain.AssessmentAttempt, +) bool { + snapshot := attempt.Snapshot() + pins := result.Pins + public := attempt.PublicSnapshot() + return reflect.DeepEqual(result.Attempt, public) && result.Outcome == snapshot.Outcome && + result.Attempt.FinishedAt != nil && snapshot.EndedAt.Equal(*result.Attempt.FinishedAt) && + pins.ProductPolicyVersionID == snapshot.Versions.ProductPolicyVersionID && + pins.ProductPolicyVersion == snapshot.Versions.ProductPolicyVersion && + pins.GradingPolicyVersionID == snapshot.Versions.GradingPolicyVersionID && + pins.OpeningID == snapshot.Versions.OpeningID && pins.OpeningManifestHash == snapshot.Versions.OpeningManifestHash && + pins.TrainingBindingID == snapshot.Versions.TrainingBindingID && + pins.TrainingManifestHash == snapshot.Versions.TrainingManifestHash && + pins.BankVersion == snapshot.Versions.BankVersion && pins.AlgorithmVersion == snapshot.Versions.AlgorithmVersion +} + +func assessmentAttemptResultFromSnapshot( + snapshot domain.AssessmentAttemptResultSnapshot, +) AssessmentAttemptResult { + return AssessmentAttemptResult{ + Attempt: snapshot.Attempt, Outcome: snapshot.Outcome, + NotDeterminedReason: snapshot.NotDeterminedReason, + BasicScore: snapshot.BasicScore, Limitations: append([]string{}, snapshot.Limitations...), + Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt, + } +} diff --git a/backend/internal/usecase/assessment/signal.go b/backend/internal/usecase/assessment/signal.go new file mode 100644 index 0000000..c31523f --- /dev/null +++ b/backend/internal/usecase/assessment/signal.go @@ -0,0 +1,380 @@ +package assessment + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + assessmentSignalOperation = "assessment_attempt.signals" + assessmentSignalRateWindow = time.Minute + assessmentSignalMaxReceipts = int64(30) + assessmentSignalMaxEvents = int64(10000) + assessmentSignalTimestampSkew = 5 * time.Minute + assessmentSignalMaximumBodySize = 32 << 10 + assessmentSignalMaximumEvents = 50 +) + +var ( + ErrAttemptSignalForbidden = errors.New("assessment signals are forbidden") + ErrAttemptSignalConsentRequired = errors.New("assessment signals require current C3 consent") + ErrAttemptSignalStateConflict = errors.New("assessment attempt cannot accept signals") + ErrAttemptSignalRateLimited = errors.New("assessment signal receipt rate limit exceeded") + ErrInvalidAttemptSignalRequest = errors.New("invalid assessment signal request") +) + +// SignalRateLimitError carries the first time a new receipt can be retried. +// Its message contains no candidate, attempt, or event data. +type SignalRateLimitError struct { + RetryAt time.Time +} + +func (limitError *SignalRateLimitError) Error() string { + return ErrAttemptSignalRateLimited.Error() +} + +func (limitError *SignalRateLimitError) Unwrap() error { + return ErrAttemptSignalRateLimited +} + +// SignalService stores bounded client-reported event metadata for real +// assessment attempts. The signals do not participate in grading. +type SignalService struct { + transactor outbound.Transactor + keyring Keyring + clock func() time.Time +} + +func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) { + if transactor == nil || keyring == nil || clock == nil { + return nil, errors.New("assessment.NewSignalService - every dependency must be set") + } + return &SignalService{transactor: transactor, keyring: keyring, clock: clock}, nil +} + +type RecordSignalsCommand struct { + ActorID uuid.UUID + AttemptID domain.AssessmentAttemptID + IdempotencyKey string + Events []domain.AssessmentSignalEvent +} + +type canonicalSignalRequest struct { + AttemptID string `json:"attempt_id"` + Events []canonicalSignalEvent `json:"events"` +} + +type canonicalSignalEvent struct { + Kind domain.AssessmentSignalKind `json:"kind"` + ItemInstanceID uuid.UUID `json:"item_instance_id"` + OccurredAt time.Time `json:"occurred_at"` + DurationMS *int32 `json:"duration_ms,omitempty"` + SizeBytes *int32 `json:"size_bytes,omitempty"` +} + +type signalIdempotencyRequest struct { + scope outbound.AssessmentAttemptIdempotencyScope + record outbound.IdempotencyRecord +} + +// RecordSignals stores all events in a batch or stores none. A replay returns +// the original receipt without rechecking or repeating storage effects. +func (service *SignalService) RecordSignals( + ctx context.Context, + command RecordSignalsCommand, +) (domain.AssessmentSignalReceipt, error) { + const location = "SignalService.RecordSignals" + canonicalEvents, body, err := canonicalSignalBody(command) + if err != nil { + return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate request: %w", location, err) + } + now, err := assessmentIdempotencyTime(service.clock()) + if err != nil { + return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate application time: %w", location, err) + } + request, err := service.prepareSignalIdempotency(command, body, now) + if err != nil { + return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - prepare idempotency: %w", location, err) + } + + var receipt domain.AssessmentSignalReceipt + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil { + return err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return fmt.Errorf("%s - reserve idempotency: %w", location, err) + } + repository := unit.AssessmentSignals() + if !created { + if stored.Fingerprint != request.record.Fingerprint { + return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused) + } + if err := requireReplayableSignalAttempt(ctx, unit, command); err != nil { + return fmt.Errorf("%s - verify owner-scoped attempt before replay: %w", location, err) + } + receipt, err = repository.GetOutcome(ctx, request.scope) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentSignalOutcomeNotFound) { + if attemptErr := requireReplayableSignalAttempt(ctx, unit, command); attemptErr != nil { + return fmt.Errorf("%s - verify attempt after missing receipt: %w", location, attemptErr) + } + } + return fmt.Errorf("%s - read immutable receipt: %w", location, err) + } + return nil + } + if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil { + return fmt.Errorf("%s - remove expired receipt: %w", location, err) + } + return service.recordNewSignals(ctx, unit, repository, command, canonicalEvents, request.scope, &receipt) + }) + if err != nil { + return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return receipt, nil +} + +func requireReplayableSignalAttempt(ctx context.Context, unit outbound.UnitOfWork, command RecordSignalsCommand) error { + const location = "SignalService.requireReplayableSignalAttempt" + kind, err := unit.AssessmentAttempts().GetKindForCandidate(ctx, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return fmt.Errorf("%s - owner-scoped attempt is missing: %w", location, ErrAttemptNotFound) + } + if err != nil { + return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) + } + if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective { + return fmt.Errorf("%s - training attempts do not have signal receipts: %w", location, ErrAttemptSignalStateConflict) + } + return nil +} + +func (service *SignalService) recordNewSignals( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.AssessmentSignalRepository, + command RecordSignalsCommand, + events []domain.AssessmentSignalEvent, + scope outbound.AssessmentAttemptIdempotencyScope, + receipt *domain.AssessmentSignalReceipt, +) error { + const location = "SignalService.recordNewSignals" + attempt, err := lockAttemptForSignals(ctx, unit, command) + if err != nil { + return fmt.Errorf("%s - lock attempt and C3 consent: %w", location, err) + } + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err) + } + databaseTime = databaseTime.UTC().Truncate(time.Microsecond) + if !attempt.IsActive() || !databaseTime.Before(attempt.ExpiresAt()) { + return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptSignalStateConflict) + } + if err := validateSignalItemsAndTimes(attempt, events, databaseTime); err != nil { + return fmt.Errorf("%s - validate item binding and timestamp: %w", location, err) + } + if err := checkSignalReceiptRate(ctx, repository, attempt.ID(), databaseTime); err != nil { + return fmt.Errorf("%s - check receipt rate: %w", location, err) + } + status, acceptedCount, err := service.persistSignalBatch(ctx, repository, attempt.ID(), events, databaseTime) + if err != nil { + return fmt.Errorf("%s - persist bounded event batch: %w", location, err) + } + newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime) + if err != nil { + return fmt.Errorf("%s - build receipt: %w", location, err) + } + if err := repository.SaveOutcome(ctx, scope, attempt.ID(), newReceipt); err != nil { + return fmt.Errorf("%s - store immutable receipt: %w", location, err) + } + *receipt = newReceipt + return nil +} + +func lockAttemptForSignals( + ctx context.Context, + unit outbound.UnitOfWork, + command RecordSignalsCommand, +) (domain.AssessmentAttempt, error) { + const location = "SignalService.lockAttemptForSignals" + attempts := unit.AssessmentAttempts() + kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound) + } + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err) + } + if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - training attempts do not accept signals: %w", location, ErrAttemptSignalStateConflict) + } + if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil { + if errors.Is(err, outbound.ErrConsentNotFound) { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptSignalConsentRequired) + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock current C3 consent: %w", location, err) + } + attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID) + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound) + } + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) + } + if attempt.Kind() != kind { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) + } + return attempt, nil +} + +func checkSignalReceiptRate( + ctx context.Context, + repository outbound.AssessmentSignalRepository, + attemptID domain.AssessmentAttemptID, + databaseTime time.Time, +) error { + const location = "SignalService.checkSignalReceiptRate" + count, oldest, err := repository.CountRecentOutcomes(ctx, attemptID, databaseTime.Add(-assessmentSignalRateWindow)) + if err != nil { + return fmt.Errorf("%s - count recent receipts: %w", location, err) + } + if count < assessmentSignalMaxReceipts { + return nil + } + retryAt := oldest.Add(assessmentSignalRateWindow).UTC().Truncate(time.Microsecond) + if !retryAt.After(databaseTime) { + retryAt = databaseTime.Add(time.Second).Truncate(time.Second) + } + return fmt.Errorf("%s - wait for the next receipt window: %w", location, &SignalRateLimitError{RetryAt: retryAt}) +} + +func (service *SignalService) persistSignalBatch( + ctx context.Context, + repository outbound.AssessmentSignalRepository, + attemptID domain.AssessmentAttemptID, + events []domain.AssessmentSignalEvent, + databaseTime time.Time, +) (domain.AssessmentSignalReceiptStatus, int32, error) { + const location = "SignalService.persistSignalBatch" + acceptedCount, err := assessmentSignalEventCount(len(events)) + if err != nil { + return "", 0, fmt.Errorf("%s - event count is invalid: %w", location, err) + } + storedCount, err := repository.CountAttemptEvents(ctx, attemptID) + if err != nil { + return "", 0, fmt.Errorf("%s - count stored events: %w", location, err) + } + if storedCount+int64(len(events)) > assessmentSignalMaxEvents { + return domain.AssessmentSignalReceiptSaturated, 0, nil + } + batchID, err := uuid.NewV7() + if err != nil { + return "", 0, fmt.Errorf("%s - generate batch ID: %w", location, err) + } + batch, err := domain.NewAssessmentSignalBatch(batchID, attemptID, databaseTime, events) + if err != nil { + return "", 0, fmt.Errorf("%s - build event batch: %w", location, err) + } + if err := repository.SaveBatch(ctx, batch); err != nil { + return "", 0, fmt.Errorf("%s - store event batch: %w", location, err) + } + return domain.AssessmentSignalReceiptAccepted, acceptedCount, nil +} + +func assessmentSignalEventCount(count int) (int32, error) { + if count < 1 || count > assessmentSignalMaximumEvents { + return 0, ErrInvalidAttemptSignalRequest + } + return int32(count), nil +} + +func (service *SignalService) prepareSignalIdempotency( + command RecordSignalsCommand, + body []byte, + now time.Time, +) (signalIdempotencyRequest, error) { + if !validAttemptIdempotencyKey(command.IdempotencyKey) { + return signalIdempotencyRequest{}, ErrInvalidAttemptKey + } + expiresAt := now.Add(outbound.IdempotencyRetention) + if !expiresAt.After(now) || expiresAt.Year() > 9999 { + return signalIdempotencyRequest{}, ErrInvalidAttemptSignalRequest + } + scopeBytes := service.keyring.IdempotencyScope(assessmentSignalOperation, command.IdempotencyKey, command.ActorID.String()) + return signalIdempotencyRequest{ + scope: outbound.AssessmentAttemptIdempotencyScope(scopeBytes), + record: outbound.IdempotencyRecord{ + Scope: scopeBytes, Fingerprint: service.keyring.Fingerprint(body), CreatedAt: now, ExpiresAt: expiresAt, + }, + }, nil +} + +func canonicalSignalBody(command RecordSignalsCommand) ([]domain.AssessmentSignalEvent, []byte, error) { + if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || len(command.Events) == 0 || len(command.Events) > assessmentSignalMaximumEvents { + return nil, nil, ErrInvalidAttemptSignalRequest + } + canonical := canonicalSignalRequest{AttemptID: command.AttemptID.String(), Events: make([]canonicalSignalEvent, 0, len(command.Events))} + validated := make([]domain.AssessmentSignalEvent, 0, len(command.Events)) + for _, event := range command.Events { + duration, hasDuration := event.DurationMS() + size, hasSize := event.SizeBytes() + input := domain.AssessmentSignalEventInput{ + Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt(), + } + encodedEvent := canonicalSignalEvent{Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt()} + if hasDuration { + input.DurationMS = &duration + encodedEvent.DurationMS = &duration + } + if hasSize { + input.SizeBytes = &size + encodedEvent.SizeBytes = &size + } + checked, err := domain.NewAssessmentSignalEvent(input) + if err != nil { + return nil, nil, fmt.Errorf("%w", ErrInvalidAttemptSignalRequest) + } + validated = append(validated, checked) + canonical.Events = append(canonical.Events, encodedEvent) + } + body, err := json.Marshal(canonical) + if err != nil || len(body) == 0 || len(body) > assessmentSignalMaximumBodySize { + return nil, nil, ErrInvalidAttemptSignalRequest + } + return validated, body, nil +} + +func validateSignalItemsAndTimes( + attempt domain.AssessmentAttempt, + events []domain.AssessmentSignalEvent, + databaseTime time.Time, +) error { + snapshot := attempt.Snapshot() + itemIDs := make(map[uuid.UUID]struct{}, len(snapshot.Items)) + for _, item := range snapshot.Items { + itemIDs[item.ID] = struct{}{} + } + earliest := snapshot.CreatedAt.UTC().Add(-assessmentSignalTimestampSkew) + latest := databaseTime.Add(assessmentSignalTimestampSkew) + for _, event := range events { + if _, exists := itemIDs[event.ItemInstanceID()]; !exists { + return ErrInvalidAttemptSignalRequest + } + occurredAt := event.OccurredAt() + if occurredAt.Before(earliest) || occurredAt.After(latest) { + return ErrInvalidAttemptSignalRequest + } + } + return nil +} diff --git a/backend/internal/usecase/assessment/signal_test.go b/backend/internal/usecase/assessment/signal_test.go new file mode 100644 index 0000000..2608555 --- /dev/null +++ b/backend/internal/usecase/assessment/signal_test.go @@ -0,0 +1,120 @@ +package assessment + +import ( + "crypto/sha256" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +type signalKeyring struct{} + +func (signalKeyring) IdempotencyScope(operation, key, principal string) [32]byte { + return sha256.Sum256([]byte(operation + ":" + key + ":" + principal)) +} + +func (signalKeyring) Fingerprint(body []byte) [32]byte { + return sha256.Sum256(body) +} + +func TestCanonicalSignalBodyContainsOnlyBoundedAllowlistedFields(t *testing.T) { + attemptID, itemID := domain.AssessmentAttemptID(uuid.New()), uuid.New() + at := time.Date(2026, time.October, 7, 12, 0, 0, 987654321, time.FixedZone("offset", 3*60*60)) + size := int32(128) + event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{ + Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: at, SizeBytes: &size, + }) + if err != nil { + t.Fatalf("NewAssessmentSignalEvent() error = %v", err) + } + validated, encoded, err := canonicalSignalBody(RecordSignalsCommand{ + ActorID: uuid.New(), AttemptID: attemptID, Events: []domain.AssessmentSignalEvent{event}, + }) + if err != nil { + t.Fatalf("canonicalSignalBody() error = %v", err) + } + if len(validated) != 1 || int64(len(encoded)) > assessmentSignalMaximumBodySize { + t.Fatalf("canonical body has %d events and %d bytes", len(validated), len(encoded)) + } + var document map[string]any + if err := json.Unmarshal(encoded, &document); err != nil { + t.Fatalf("json.Unmarshal() error = %v", err) + } + if document["attempt_id"] != attemptID.String() || len(document) != 2 { + t.Fatalf("canonical request keys/value = %+v", document) + } + events, ok := document["events"].([]any) + if !ok || len(events) != 1 { + t.Fatalf("canonical events = %#v", document["events"]) + } + fields, ok := events[0].(map[string]any) + if !ok { + t.Fatalf("canonical event = %#v", events[0]) + } + if fields["kind"] != "paste" || fields["item_instance_id"] != itemID.String() || fields["size_bytes"] != float64(size) { + t.Fatalf("canonical event fields = %+v", fields) + } + if _, ok := fields["occurred_at"].(string); !ok || len(fields) != 4 { + t.Fatalf("canonical event includes unexpected fields: %+v", fields) + } + for _, forbidden := range []string{"answer", "answer_text", "clipboard", "content", "organization_id", "score"} { + if strings.Contains(string(encoded), forbidden) { + t.Errorf("canonical request contains forbidden term %q", forbidden) + } + } +} + +func TestSignalIdempotencyFingerprintBindsAttemptAndRejectsInvalidKeys(t *testing.T) { + actorID, itemID := uuid.New(), uuid.New() + at := time.Now().UTC().Truncate(time.Microsecond) + event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{ + Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: at, + }) + if err != nil { + t.Fatalf("NewAssessmentSignalEvent() error = %v", err) + } + service := &SignalService{keyring: signalKeyring{}} + command := RecordSignalsCommand{ActorID: actorID, AttemptID: domain.AssessmentAttemptID(uuid.New()), IdempotencyKey: "same-key", Events: []domain.AssessmentSignalEvent{event}} + _, firstBody, err := canonicalSignalBody(command) + if err != nil { + t.Fatalf("canonicalSignalBody(first) error = %v", err) + } + first, err := service.prepareSignalIdempotency(command, firstBody, at) + if err != nil { + t.Fatalf("prepareSignalIdempotency(first) error = %v", err) + } + command.AttemptID = domain.AssessmentAttemptID(uuid.New()) + _, secondBody, err := canonicalSignalBody(command) + if err != nil { + t.Fatalf("canonicalSignalBody(second) error = %v", err) + } + second, err := service.prepareSignalIdempotency(command, secondBody, at) + if err != nil { + t.Fatalf("prepareSignalIdempotency(second) error = %v", err) + } + if first.scope != second.scope || first.record.Fingerprint == second.record.Fingerprint { + t.Fatal("same actor key should share its scope and reject a different attempt body") + } + for _, invalidKey := range []string{"", strings.Repeat("a", maxAttemptIdempotencyKeyBytes+1), "key with spaces"} { + command.IdempotencyKey = invalidKey + if _, err := service.prepareSignalIdempotency(command, secondBody, at); !errors.Is(err, ErrInvalidAttemptKey) { + t.Errorf("prepareSignalIdempotency(%q) error = %v, want ErrInvalidAttemptKey", invalidKey, err) + } + } +} + +func TestCanonicalSignalBodyRejectsUnbuiltEvents(t *testing.T) { + _, _, err := canonicalSignalBody(RecordSignalsCommand{ + ActorID: uuid.New(), AttemptID: domain.AssessmentAttemptID(uuid.New()), + Events: []domain.AssessmentSignalEvent{{}}, + }) + if err == nil { + t.Fatal("canonicalSignalBody() accepted a zero event") + } +} diff --git a/backend/internal/usecase/candidateprivacy/service.go b/backend/internal/usecase/candidateprivacy/service.go new file mode 100644 index 0000000..ca2c872 --- /dev/null +++ b/backend/internal/usecase/candidateprivacy/service.go @@ -0,0 +1,565 @@ +// Package candidateprivacy implements candidate-owned publication and privacy +// settings. Every command is scoped to the authenticated candidate. +package candidateprivacy + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + ErrForbidden = errors.New("candidate privacy operation is forbidden") + ErrEmailNotVerified = errors.New("candidate email is not verified") + ErrPrivacyServiceUnavailable = errors.New("candidate privacy service is unavailable") + ErrHiddenOrganizationNotFound = errors.New("hidden organization not found") +) + +// Dependencies configure the candidate privacy settings service. +type Dependencies struct { + Transactor outbound.Transactor + Clock func() time.Time +} + +// Service applies candidate-owned privacy settings in one transaction. +type Service struct { + transactor outbound.Transactor + clock func() time.Time +} + +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Clock == nil { + return nil, fmt.Errorf("candidateprivacy.NewService - dependencies are missing: %w", ErrPrivacyServiceUnavailable) + } + return &Service{transactor: deps.Transactor, clock: deps.Clock}, nil +} + +func (service *Service) GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) { + const location = "candidateprivacy.Service.GetMyPrivacySettings" + var result outbound.CandidatePrivacySettings + at, err := service.now() + if err != nil { + return result, err + } + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, userID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + result, err = repository.ReadSettings(ctx, userID) + if err != nil { + return fmt.Errorf("%s - read candidate settings: %w", location, err) + } + result.AsOf = at + return nil + }) + if err != nil { + return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) SetMyPublication( + ctx context.Context, + userID uuid.UUID, + expectedVersion int64, + state domain.PublicationState, + fields []domain.CardField, +) (domain.Publication, error) { + const location = "candidateprivacy.Service.SetMyPublication" + request, err := domain.NewPublicationRequest(state, fields) + if err != nil { + return domain.Publication{}, err + } + at, err := service.now() + if err != nil { + return domain.Publication{}, err + } + var result domain.Publication + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, userID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + activeC2, err := currentC2ForPublication(ctx, repository, userID, location) + if err != nil { + return err + } + settings, err := repository.ReadSettings(ctx, userID) + if err != nil { + return fmt.Errorf("%s - read current publication: %w", location, err) + } + change, err := settings.Publication.Apply(request, expectedVersion, activeC2, at) + if err != nil { + return err + } + result = change.Publication + if !change.Changed { + return nil + } + return persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location) + }) + if err != nil { + return domain.Publication{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func currentC2ForPublication( + ctx context.Context, + repository outbound.PrivacySettingsRepository, + userID uuid.UUID, + location string, +) (uuid.UUID, error) { + activeC2, err := repository.LockCurrentC2ForPublication(ctx, userID) + if errors.Is(err, outbound.ErrConsentNotFound) { + return uuid.Nil, nil + } + if err != nil { + return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location, err) + } + return activeC2, nil +} + +func persistPublicationChange( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.PrivacySettingsRepository, + userID uuid.UUID, + expectedVersion int64, + change domain.PublicationChange, + at time.Time, + location string, +) error { + if err := repository.SavePublication(ctx, change.Publication, expectedVersion); err != nil { + return fmt.Errorf("%s - save publication: %w", location, err) + } + if change.Event == domain.PrivacyEventPublicationClosed { + if err := closeContactGrants(ctx, unit.PrivacyView(), userID, uuid.Nil, at, location, "publication close"); err != nil { + return err + } + } + event, err := domain.NewPublicationEvent(change, at) + if err != nil { + return fmt.Errorf("%s - build publication history: %w", location, err) + } + if err := repository.RecordPrivacyEvent(ctx, event); err != nil { + return fmt.Errorf("%s - record publication history: %w", location, err) + } + if change.Event != domain.PrivacyEventPublicationClosed { + return nil + } + if err := appendVisibilityClosed(ctx, unit, userID, uuid.Nil, "publication_closed", at, event.ID()); err != nil { + return fmt.Errorf("%s - append visibility closure intent: %w", location, err) + } + return nil +} + +func closeContactGrants( + ctx context.Context, + repository outbound.ContactAccessRepository, + candidateID, organizationID uuid.UUID, + at time.Time, + location, reason string, +) error { + if repository == nil { + return ErrPrivacyServiceUnavailable + } + if err := repository.CloseForVisibility(ctx, candidateID, organizationID, at); err != nil { + return fmt.Errorf("%s - close contact grants after %s: %w", location, reason, err) + } + return nil +} + +func (service *Service) SetMySearchStatus( + ctx context.Context, + userID uuid.UUID, + expectedVersion int64, + value domain.SearchStatusValue, +) (domain.SearchStatus, time.Time, error) { + const location = "candidateprivacy.Service.SetMySearchStatus" + at, err := service.now() + if err != nil { + return domain.SearchStatus{}, time.Time{}, err + } + var result domain.SearchStatus + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, userID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + settings, err := repository.ReadSettings(ctx, userID) + if err != nil { + return fmt.Errorf("%s - read current search status: %w", location, err) + } + var confirmation domain.SearchStatusConfirmation + if value == domain.SearchStatusLooking && expectedVersion == settings.SearchStatus.Version() { + policyVersion, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at) + if err != nil { + return fmt.Errorf("%s - read effective product policy: %w", location, err) + } + confirmation, err = domain.NewSearchStatusConfirmation(policyVersion.ID(), policyVersion.Policy().SearchStatus) + if err != nil { + return fmt.Errorf("%s - build search status confirmation: %w", location, err) + } + } + change, err := settings.SearchStatus.Apply(value, expectedVersion, confirmation, at) + if err != nil { + return err + } + result = change.Status + if !change.Changed { + return nil + } + if err := repository.SaveSearchStatus(ctx, change.Status, expectedVersion, at); err != nil { + return fmt.Errorf("%s - save search status: %w", location, err) + } + event, err := domain.NewSearchStatusEvent(change, at) + if err != nil { + return fmt.Errorf("%s - build search status history: %w", location, err) + } + if err := repository.RecordPrivacyEvent(ctx, event); err != nil { + return fmt.Errorf("%s - record search status history: %w", location, err) + } + return nil + }) + if err != nil { + return domain.SearchStatus{}, time.Time{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, at, nil +} + +func (service *Service) ListMyPrivacyHistory( + ctx context.Context, + query outbound.CandidatePrivacyEventListQuery, +) (outbound.CandidatePrivacyEventPage, error) { + const location = "candidateprivacy.Service.ListMyPrivacyHistory" + if err := validatePage(query.UserID, query.Limit, query.After); err != nil { + return outbound.CandidatePrivacyEventPage{}, err + } + var result outbound.CandidatePrivacyEventPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, query.UserID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + result, err = repository.ListPrivacyEvents(ctx, query) + if err != nil { + return fmt.Errorf("%s - list privacy history: %w", location, err) + } + return nil + }) + if err != nil { + return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) ListMyHiddenOrganizations( + ctx context.Context, + query outbound.HiddenOrganizationListQuery, +) (outbound.HiddenOrganizationPage, error) { + const location = "candidateprivacy.Service.ListMyHiddenOrganizations" + if err := validatePage(query.UserID, query.Limit, query.After); err != nil { + return outbound.HiddenOrganizationPage{}, err + } + var result outbound.HiddenOrganizationPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, query.UserID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + result, err = repository.ListHiddenOrganizations(ctx, query) + if err != nil { + return fmt.Errorf("%s - list hidden organizations: %w", location, err) + } + return nil + }) + if err != nil { + return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) HideOrganization( + ctx context.Context, + userID, organizationID uuid.UUID, +) (outbound.HiddenOrganizationRecord, error) { + const location = "candidateprivacy.Service.HideOrganization" + at, err := service.now() + if err != nil { + return outbound.HiddenOrganizationRecord{}, err + } + var result outbound.HiddenOrganizationRecord + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, userID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + result, err = service.hideOrganizationInTransaction(ctx, unit, repository, userID, organizationID, at, location) + return err + }) + if err != nil { + return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) hideOrganizationInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.PrivacySettingsRepository, + userID, organizationID uuid.UUID, + at time.Time, + location string, +) (outbound.HiddenOrganizationRecord, error) { + visible, err := repository.CandidateCanSeeOrganization(ctx, userID, organizationID) + if err != nil { + return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - verify organization visibility: %w", location, err) + } + result := outbound.HiddenOrganizationRecord{OrganizationID: visible.ID, OrganizationName: visible.Name} + current, err := repository.GetHiddenOrganization(ctx, userID, organizationID) + if err == nil { + result.HiddenAt = current.HiddenAt + return result, closeContactGrants(ctx, unit.PrivacyView(), userID, organizationID, at, location, "organization hiding") + } + if !errors.Is(err, outbound.ErrCandidatePrivacySettingsNotFound) { + return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - read existing hiding: %w", location, err) + } + hiddenAt, created, err := createOrganizationHiding(ctx, repository, userID, organizationID, at, location) + if err != nil { + return outbound.HiddenOrganizationRecord{}, err + } + result.HiddenAt = hiddenAt + if !created { + return result, nil + } + if err := persistOrganizationHiding(ctx, unit, repository, userID, organizationID, at, location); err != nil { + return outbound.HiddenOrganizationRecord{}, err + } + return result, nil +} + +func createOrganizationHiding( + ctx context.Context, + repository outbound.PrivacySettingsRepository, + userID, organizationID uuid.UUID, + at time.Time, + location string, +) (time.Time, bool, error) { + count, err := repository.CountHiddenOrganizations(ctx, userID) + if err != nil { + return time.Time{}, false, fmt.Errorf("%s - count hidden organizations: %w", location, err) + } + if count >= domain.MaxHiddenOrganizations { + return time.Time{}, false, outbound.ErrCandidateHiddenOrganizationLimit + } + hidden, err := domain.NewHiddenOrganization(userID, organizationID, at) + if err != nil { + return time.Time{}, false, err + } + created, err := repository.HideOrganization(ctx, hidden) + if err != nil { + return time.Time{}, false, fmt.Errorf("%s - store hiding: %w", location, err) + } + if created { + return at, true, nil + } + current, err := repository.GetHiddenOrganization(ctx, userID, organizationID) + if err != nil { + return time.Time{}, false, fmt.Errorf("%s - read concurrent hiding: %w", location, err) + } + return current.HiddenAt, false, nil +} + +func persistOrganizationHiding( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.PrivacySettingsRepository, + userID, organizationID uuid.UUID, + at time.Time, + location string, +) error { + if err := closeContactGrants(ctx, unit.PrivacyView(), userID, organizationID, at, location, "organization hiding"); err != nil { + return err + } + event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationHidden, userID, organizationID, at) + if err != nil { + return fmt.Errorf("%s - build hiding history: %w", location, err) + } + if err := repository.RecordPrivacyEvent(ctx, event); err != nil { + return fmt.Errorf("%s - record hiding history: %w", location, err) + } + if err := appendVisibilityClosed(ctx, unit, userID, organizationID, "organization_hidden", at, event.ID()); err != nil { + return fmt.Errorf("%s - append visibility closure intent: %w", location, err) + } + return nil +} + +func (service *Service) UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error { + const location = "candidateprivacy.Service.UnhideOrganization" + at, err := service.now() + if err != nil { + return err + } + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, userID); err != nil { + return err + } + repository, err := settingsRepository(unit) + if err != nil { + return err + } + deleted, err := repository.UnhideOrganization(ctx, userID, organizationID) + if err != nil { + return fmt.Errorf("%s - delete hiding: %w", location, err) + } + if !deleted { + return nil + } + event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationUnhidden, userID, organizationID, at) + if err != nil { + return fmt.Errorf("%s - build unhiding history: %w", location, err) + } + if err := repository.RecordPrivacyEvent(ctx, event); err != nil { + return fmt.Errorf("%s - record unhiding history: %w", location, err) + } + return nil + }) + if err != nil { + return fmt.Errorf("%s - run transaction: %w", location, err) + } + return nil +} + +func (service *Service) now() (time.Time, error) { + at := service.clock().UTC().Truncate(time.Microsecond) + if at.IsZero() { + return time.Time{}, fmt.Errorf("candidateprivacy.Service - clock returned zero: %w", ErrPrivacyServiceUnavailable) + } + return at, nil +} + +func validatePage(userID uuid.UUID, limit int32, after any) error { + if userID == uuid.Nil || limit < 1 || limit > outbound.MaxPrivacyPageSize { + return domain.ErrInvalidVisibility + } + switch position := after.(type) { + case nil: + case *outbound.CandidatePrivacyEventPosition: + if position != nil && (position.ID == uuid.Nil || position.OccurredAt.IsZero()) { + return domain.ErrInvalidVisibility + } + case *outbound.HiddenOrganizationPosition: + if position != nil && (position.OrganizationID == uuid.Nil || position.HiddenAt.IsZero()) { + return domain.ErrInvalidVisibility + } + default: + return domain.ErrInvalidVisibility + } + return nil +} + +func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID) error { + if userID == uuid.Nil { + return ErrForbidden + } + user, err := unit.Users().GetByID(ctx, userID) + if errors.Is(err, outbound.ErrUserNotFound) { + return ErrForbidden + } + if err != nil { + return fmt.Errorf("candidateprivacy.authorizeCandidate - read account: %w", err) + } + if user.Scenario != domain.ScenarioCandidate { + return ErrForbidden + } + if !user.EmailVerified() { + return ErrEmailNotVerified + } + return nil +} + +func settingsRepository(unit outbound.UnitOfWork) (outbound.PrivacySettingsRepository, error) { + repository := unit.PrivacySettings() + if repository == nil { + return nil, ErrPrivacyServiceUnavailable + } + return repository, nil +} + +type visibilityClosedPayload struct { + CandidateID uuid.UUID `json:"candidate_id"` + OrganizationID *uuid.UUID `json:"organization_id"` + Reason string `json:"reason"` + OccurredAt time.Time `json:"occurred_at"` + PrivacyEventID uuid.UUID `json:"privacy_event_id"` +} + +func appendVisibilityClosed( + ctx context.Context, + unit outbound.UnitOfWork, + candidateID, organizationID uuid.UUID, + reason string, + at time.Time, + privacyEventID uuid.UUID, +) error { + const location = "candidateprivacy.appendVisibilityClosed" + if candidateID == uuid.Nil || privacyEventID == uuid.Nil || at.IsZero() || + (reason != "publication_closed" && reason != "organization_hidden") || + (reason == "organization_hidden" && organizationID == uuid.Nil) || + (reason == "publication_closed" && organizationID != uuid.Nil) { + return fmt.Errorf("%s - closure facts are invalid: %w", location, domain.ErrInvalidDomainEvent) + } + var organization *uuid.UUID + if organizationID != uuid.Nil { + organization = &organizationID + } + payload, err := json.Marshal(visibilityClosedPayload{ + CandidateID: candidateID, OrganizationID: organization, Reason: reason, + OccurredAt: at.UTC().Truncate(time.Microsecond), PrivacyEventID: privacyEventID, + }) + if err != nil { + return fmt.Errorf("%s - encode payload", location) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: "privacy.visibility_closed", SchemaVersion: 1, + AggregateType: "privacy_event", AggregateID: privacyEventID, AggregateVersion: 1, Payload: payload, + }) + if err != nil { + return fmt.Errorf("%s - build event: %w", location, err) + } + writer := unit.Outbox() + if writer == nil { + return fmt.Errorf("%s - transactional outbox is unavailable: %w", location, ErrPrivacyServiceUnavailable) + } + if err := writer.Append(ctx, event); err != nil { + return fmt.Errorf("%s - append event: %w", location, err) + } + return nil +} diff --git a/backend/internal/usecase/candidateprivacy/service_test.go b/backend/internal/usecase/candidateprivacy/service_test.go new file mode 100644 index 0000000..4b73253 --- /dev/null +++ b/backend/internal/usecase/candidateprivacy/service_test.go @@ -0,0 +1,273 @@ +package candidateprivacy + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestPublicationCloseWritesHistoryAndTransactionalClosureIntentOnce(t *testing.T) { + const now = "2026-10-07T12:00:00.123456Z" + at := mustTime(t, now) + candidateID, consentID := uuid.New(), uuid.New() + initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour)) + transactor := &privacyTestTransactor{ + user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)}, + publication: initial, + } + service := mustPrivacyService(t, transactor, at) + + closed, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil) + if err != nil { + t.Fatalf("SetMyPublication(close) error = %v", err) + } + if closed.StoredState() != domain.PublicationClosed || closed.Version() != initial.Version()+1 { + t.Fatalf("close result = %s v%d, want closed v%d", closed.StoredState(), closed.Version(), initial.Version()+1) + } + if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 { + t.Fatalf("committed close effects = history %d, outbox %d, grants %d; want one each", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls)) + } + if got := transactor.sequence; fmt.Sprint(got) != "[close history outbox]" { + t.Fatalf("closure order = %v, want close -> history -> outbox", got) + } + assertVisibilityClosedEvent(t, transactor.outboxEvents[0], candidateID, uuid.Nil, transactor.history[0].ID(), at) + + _, err = service.SetMyPublication(context.Background(), candidateID, closed.Version(), domain.PublicationClosed, nil) + if err != nil { + t.Fatalf("repeated SetMyPublication(close) error = %v", err) + } + if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 { + t.Fatalf("repeated close effects = history %d, outbox %d, grants %d; want no duplicate intent", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls)) + } +} + +func TestValidatePageAcceptsTypedNilInitialCursors(t *testing.T) { + t.Parallel() + + var privacyCursor *outbound.CandidatePrivacyEventPosition + var hiddenCursor *outbound.HiddenOrganizationPosition + userID := uuid.New() + for _, test := range []struct { + name string + after any + }{ + {name: "privacy history", after: privacyCursor}, + {name: "hidden organizations", after: hiddenCursor}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + if err := validatePage(userID, 20, test.after); err != nil { + t.Fatalf("validatePage(initial cursor) error = %v, want nil", err) + } + }) + } +} + +func TestPublicationCloseRollsBackWhenClosureIntentCannotBeStored(t *testing.T) { + at := mustTime(t, "2026-10-07T12:00:00.123456Z") + candidateID, consentID := uuid.New(), uuid.New() + initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour)) + transactor := &privacyTestTransactor{ + user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)}, + publication: initial, outboxError: errors.New("outbox unavailable"), + } + service := mustPrivacyService(t, transactor, at) + + if _, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil); err == nil { + t.Fatal("SetMyPublication(close) error = nil, want closure intent failure") + } + if transactor.publication.Version() != initial.Version() || transactor.publication.StoredState() != domain.PublicationPublished { + t.Fatalf("publication after failed transaction = %s v%d, want unchanged published v%d", transactor.publication.StoredState(), transactor.publication.Version(), initial.Version()) + } + if len(transactor.history) != 0 || len(transactor.outboxEvents) != 0 || len(transactor.closureCalls) != 0 { + t.Fatalf("effects after failed transaction = history %d, outbox %d, grants %d; want rollback", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls)) + } +} + +func mustPrivacyService(t *testing.T, transactor outbound.Transactor, at time.Time) *Service { + t.Helper() + service, err := NewService(Dependencies{Transactor: transactor, Clock: func() time.Time { return at }}) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + return service +} + +func mustPublished(t *testing.T, candidateID, consentID uuid.UUID, at time.Time) domain.Publication { + t.Helper() + publication, err := domain.NewPublication(candidateID) + if err != nil { + t.Fatalf("NewPublication() error = %v", err) + } + request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack}) + if err != nil { + t.Fatalf("NewPublicationRequest() error = %v", err) + } + change, err := publication.Apply(request, 0, consentID, at) + if err != nil || !change.Changed { + t.Fatalf("Apply(publish) = %+v, %v, want change", change, err) + } + return change.Publication +} + +func assertVisibilityClosedEvent(t *testing.T, event domain.DomainEvent, candidateID, organizationID, privacyEventID uuid.UUID, at time.Time) { + t.Helper() + if event.EventType() != "privacy.visibility_closed" || event.SchemaVersion() != 1 || + event.AggregateType() != "privacy_event" || event.AggregateID() != privacyEventID || event.AggregateVersion() != 1 { + t.Fatalf("closure event identity = %s v%d %s/%s v%d", event.EventType(), event.SchemaVersion(), event.AggregateType(), event.AggregateID(), event.AggregateVersion()) + } + var payload struct { + CandidateID uuid.UUID `json:"candidate_id"` + OrganizationID *uuid.UUID `json:"organization_id"` + Reason string `json:"reason"` + OccurredAt time.Time `json:"occurred_at"` + PrivacyEventID uuid.UUID `json:"privacy_event_id"` + } + if err := json.Unmarshal(event.Payload(), &payload); err != nil { + t.Fatalf("decode closure payload: %v", err) + } + if payload.CandidateID != candidateID || payload.Reason != "publication_closed" || + payload.PrivacyEventID != privacyEventID || !payload.OccurredAt.Equal(at) || payload.OrganizationID != nil || organizationID != uuid.Nil { + t.Fatalf("closure payload = %+v", payload) + } +} + +func mustTime(t *testing.T, value string) time.Time { + t.Helper() + at, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + t.Fatalf("parse test time: %v", err) + } + return at +} + +func timePointer(value time.Time) *time.Time { return &value } + +type privacyTestTransactor struct { + user domain.User + publication domain.Publication + history []domain.PrivacyEvent + outboxEvents []domain.DomainEvent + closureCalls []privacyClosureCall + sequence []string + outboxError error +} + +type privacyClosureCall struct { + candidateID uuid.UUID + organizationID uuid.UUID + at time.Time +} + +func (transactor *privacyTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error { + draft := &privacyTestTransactor{ + user: transactor.user, publication: transactor.publication, + history: append([]domain.PrivacyEvent(nil), transactor.history...), + outboxEvents: append([]domain.DomainEvent(nil), transactor.outboxEvents...), + closureCalls: append([]privacyClosureCall(nil), transactor.closureCalls...), + sequence: append([]string(nil), transactor.sequence...), outboxError: transactor.outboxError, + } + unit := privacyTestUnit{ + users: privacyTestUsers{user: draft.user}, + settings: privacyTestSettings{transactor: draft}, + view: privacyTestView{transactor: draft}, + outbox: privacyTestOutbox{transactor: draft}, + } + if err := fn(ctx, unit); err != nil { + return err + } + transactor.publication = draft.publication + transactor.history = draft.history + transactor.outboxEvents = draft.outboxEvents + transactor.closureCalls = draft.closureCalls + transactor.sequence = draft.sequence + return nil +} + +type privacyTestUnit struct { + outbound.UnitOfWork + + users outbound.UserRepository + settings outbound.PrivacySettingsRepository + view outbound.PrivacyViewRepository + outbox outbound.OutboxWriter +} + +func (unit privacyTestUnit) Users() outbound.UserRepository { return unit.users } +func (unit privacyTestUnit) PrivacySettings() outbound.PrivacySettingsRepository { + return unit.settings +} +func (unit privacyTestUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view } +func (unit privacyTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox } + +type privacyTestUsers struct { + outbound.UserRepository + + user domain.User +} + +func (users privacyTestUsers) GetByID(context.Context, uuid.UUID) (domain.User, error) { + return users.user, nil +} + +type privacyTestSettings struct { + outbound.PrivacySettingsRepository + + transactor *privacyTestTransactor +} + +func (settings privacyTestSettings) ReadSettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) { + return outbound.CandidatePrivacySettings{Publication: settings.transactor.publication}, nil +} + +func (settings privacyTestSettings) LockCurrentC2ForPublication(context.Context, uuid.UUID) (uuid.UUID, error) { + return settings.transactor.publication.ConsentRecordID(), nil +} + +func (settings privacyTestSettings) SavePublication(_ context.Context, publication domain.Publication, _ int64) error { + settings.transactor.publication = publication + return nil +} + +func (settings privacyTestSettings) RecordPrivacyEvent(_ context.Context, event domain.PrivacyEvent) error { + settings.transactor.history = append(settings.transactor.history, event) + settings.transactor.sequence = append(settings.transactor.sequence, "history") + return nil +} + +type privacyTestView struct { + outbound.PrivacyViewRepository + + transactor *privacyTestTransactor +} + +func (view privacyTestView) CloseForVisibility(_ context.Context, candidateID, organizationID uuid.UUID, at time.Time) error { + view.transactor.closureCalls = append(view.transactor.closureCalls, privacyClosureCall{ + candidateID: candidateID, organizationID: organizationID, at: at, + }) + view.transactor.sequence = append(view.transactor.sequence, "close") + return nil +} + +type privacyTestOutbox struct { + outbound.OutboxWriter + + transactor *privacyTestTransactor +} + +func (outbox privacyTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error { + if outbox.transactor.outboxError != nil { + return outbox.transactor.outboxError + } + outbox.transactor.outboxEvents = append(outbox.transactor.outboxEvents, events...) + outbox.transactor.sequence = append(outbox.transactor.sequence, "outbox") + return nil +} diff --git a/backend/internal/usecase/candidateview/contact_access_test.go b/backend/internal/usecase/candidateview/contact_access_test.go new file mode 100644 index 0000000..3329e33 --- /dev/null +++ b/backend/internal/usecase/candidateview/contact_access_test.go @@ -0,0 +1,254 @@ +package candidateview + +import ( + "bytes" + "context" + "errors" + "slices" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type contactAccessFixture struct { + fields domain.ContactFieldSet + grantActive bool + workflowAccept bool + audits []domain.CandidateCardAccess +} + +func TestCurrentContactFieldsUsesOnlyCurrentGrantFields(t *testing.T) { + t.Parallel() + + selected, err := domain.NewContactFieldSet(domain.ContactFieldPhone, domain.ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + full, err := domain.NewContactFieldSet( + domain.ContactFieldEmail, domain.ContactFieldFullName, + domain.ContactFieldPhone, domain.ContactFieldTelegram, + ) + if err != nil { + t.Fatalf("NewContactFieldSet(full) error = %v", err) + } + + for _, test := range []struct { + name string + grantFields domain.ContactFieldSet + grantActive bool + workflowAccept bool + wantFields []domain.ContactField + wantError error + }{ + { + name: "active invitation C4 returns only selected fields", + grantFields: selected, grantActive: true, workflowAccept: true, + wantFields: []domain.ContactField{domain.ContactFieldEmail, domain.ContactFieldPhone}, + }, + { + name: "accepted workflow without a C4 grant remains closed", + grantFields: full, workflowAccept: true, wantError: outbound.ErrContactAccessClosed, + }, + { + name: "revoked C4 remains closed after workflow acceptance", + grantFields: selected, workflowAccept: true, wantError: outbound.ErrContactAccessClosed, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + service, fixture, actorID, organizationID, handle := newContactAccessService(t, test.grantFields, test.grantActive, test.workflowAccept) + + got, err := service.CurrentContactFields(context.Background(), actorID, organizationID, handle) + if test.wantError != nil { + if !errors.Is(err, test.wantError) { + t.Fatalf("CurrentContactFields() error = %v, want %v", err, test.wantError) + } + if len(fixture.audits) != 0 { + t.Fatalf("closed contact read recorded audits: %v", fixture.audits) + } + return + } + if err != nil { + t.Fatalf("CurrentContactFields() error = %v", err) + } + if gotFields := got.Fields(); !slices.Equal(gotFields, test.wantFields) { + t.Fatalf("CurrentContactFields() fields = %v, want %v", gotFields, test.wantFields) + } + if len(fixture.audits) != 1 || fixture.audits[0].Kind() != domain.CandidateCardAccessContactRead || + !slices.Equal(fixture.audits[0].FieldCodes(), []string{"email", "phone"}) { + t.Fatalf("contact read audit = %v, want only selected email and phone codes", fixture.audits) + } + }) + } +} + +func newContactAccessService( + t *testing.T, + fields domain.ContactFieldSet, + grantActive, workflowAccepted bool, +) (*Service, *contactAccessFixture, uuid.UUID, uuid.UUID, string) { + t.Helper() + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + actorID, candidateID := uuid.New(), uuid.New() + organization, membership := newContactAccessOrganization(t, actorID, now) + organizationID := organization.ID() + actor := domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &now} + candidate := domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now} + users := contactAccessUsers{users: map[uuid.UUID]domain.User{actorID: actor, candidateID: candidate}} + organizations := contactAccessOrganizations{organization: organization, membership: membership} + publication, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldStack}) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + source, err := domain.NewCandidateViewSource(candidateID, publication, domain.CandidateViewProfile{}, nil, nil, nil) + if err != nil { + t.Fatalf("NewCandidateViewSource() error = %v", err) + } + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("contact-view-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + handle, err := key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + fixture := &contactAccessFixture{ + fields: fields, grantActive: grantActive, workflowAccept: workflowAccepted, + } + viewRepository := contactAccessViewRepository{fixture: fixture, source: source} + unit := contactAccessUnit{users: users, organizations: organizations, view: viewRepository} + service, err := NewService(Dependencies{ + Transactor: contactAccessTransactor{unit: unit}, + Projector: contactAccessProjector{key: key, source: source}, + PseudonymKey: key, Quota: func(context.Context, outbound.UnitOfWork, domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return outbound.CompanyQuotaDecision{Allowed: true}, nil + }, Clock: func() time.Time { return now }, + }) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + return service, fixture, actorID, organizationID, handle +} + +func newContactAccessOrganization(t *testing.T, actorID uuid.UUID, at time.Time) (domain.Organization, domain.Membership) { + t.Helper() + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{ + Name: "Example Company", Description: "A sample company", Sphere: "Technology", + Contacts: domain.OrganizationContactsInput{Website: "https://example.com", Email: "jobs@example.com", Phone: "+12025550101", Telegram: "@examplejobs"}, + Representatives: []domain.OrganizationRepresentativeInput{{Name: "Example Person", JobTitle: "Recruiter"}}, + }) + if err != nil { + t.Fatalf("NewOrganizationProfile() error = %v", err) + } + organization, err := domain.NewOrganization(profile, at) + if err != nil { + t.Fatalf("NewOrganization() error = %v", err) + } + membership, err := domain.NewOwnerMembership(organization.ID(), actorID, at) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + return organization, membership +} + +type contactAccessTransactor struct{ unit outbound.UnitOfWork } + +func (transactor contactAccessTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error { + return fn(ctx, transactor.unit) +} + +type contactAccessUnit struct { + outbound.UnitOfWork + + users outbound.UserRepository + organizations outbound.OrganizationRepository + view outbound.PrivacyViewRepository +} + +func (unit contactAccessUnit) Users() outbound.UserRepository { return unit.users } +func (unit contactAccessUnit) Organizations() outbound.OrganizationRepository { + return unit.organizations +} +func (unit contactAccessUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view } + +type contactAccessUsers struct { + outbound.UserRepository + + users map[uuid.UUID]domain.User +} + +func (repository contactAccessUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +type contactAccessOrganizations struct { + outbound.OrganizationRepository + + organization domain.Organization + membership domain.Membership +} + +func (repository contactAccessOrganizations) LockActiveMembership(context.Context, uuid.UUID, uuid.UUID) (domain.Membership, error) { + return repository.membership, nil +} +func (repository contactAccessOrganizations) GetForMember(context.Context, uuid.UUID, uuid.UUID) (domain.Organization, domain.Membership, error) { + return repository.organization, repository.membership, nil +} + +type contactAccessViewRepository struct { + outbound.PrivacyViewRepository + + fixture *contactAccessFixture + source domain.CandidateViewSource +} + +func (repository contactAccessViewRepository) ListVisibleCandidateViewSources(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) { + return []domain.CandidateViewSource{repository.source}, nil +} +func (contactAccessViewRepository) LockCandidateAccountForView(context.Context, uuid.UUID) error { + return nil +} +func (contactAccessViewRepository) LockCurrentC2ForView(context.Context, uuid.UUID) (uuid.UUID, error) { + return uuid.New(), nil +} +func (contactAccessViewRepository) LockVisiblePublicationForView(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (bool, error) { + return true, nil +} +func (repository contactAccessViewRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) { + if !repository.fixture.grantActive { + return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed + } + return repository.fixture.fields, nil +} +func (repository contactAccessViewRepository) RecordCandidateCardAccess(_ context.Context, access domain.CandidateCardAccess) error { + repository.fixture.audits = append(repository.fixture.audits, access) + return nil +} + +type contactAccessProjector struct { + key domain.CandidateViewPseudonymKey + source domain.CandidateViewSource +} + +func (projector contactAccessProjector) ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error) { + if len(sources) != 1 || sources[0].CandidateID() != projector.source.CandidateID() { + return nil, errors.New("contact access test projector received an unexpected source") + } + pseudonym, err := projector.key.ForOrganization(organizationID, projector.source.CandidateID()) + if err != nil { + return nil, err + } + return []domain.AnonymousCandidateViewDTO{{Pseudonym: pseudonym}}, nil +} + +func (projector contactAccessProjector) PreviewSource(domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error) { + return domain.AnonymousCandidateViewDTO{}, errors.New("preview is not part of the contact access test") +} diff --git a/backend/internal/usecase/candidateview/service.go b/backend/internal/usecase/candidateview/service.go new file mode 100644 index 0000000..32eba82 --- /dev/null +++ b/backend/internal/usecase/candidateview/service.go @@ -0,0 +1,515 @@ +// Package candidateview applies current publication, membership, hidden- +// organization, cohort, and quota rules to anonymous candidate reads. +package candidateview + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + ErrForbidden = errors.New("candidate view is forbidden") + ErrCandidateCardNotFound = errors.New("candidate card not found") + ErrInvalidCandidateHandle = errors.New("candidate handle is invalid") + ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read") + ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable") + ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted") +) + +const maxCohortStabilizationPasses = 8 + +// Projector builds the shared, strict anonymous-card projection. +type Projector interface { + ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error) + PreviewSource(source domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error) +} + +// CardViewQuota reserves the current policy's distinct card-view allowance. +// Bootstrap adapts the shared company-quota usecase without making this +// read-policy package depend on another usecase package. +type CardViewQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) + +// Dependencies configure the stateless candidate-view policy service. +type Dependencies struct { + Transactor outbound.Transactor + Projector Projector + PseudonymKey domain.CandidateViewPseudonymKey + Quota CardViewQuota + Clock func() time.Time +} + +// Service rechecks private visibility state in a transaction for each read. +type Service struct { + transactor outbound.Transactor + projector Projector + pseudonymKey domain.CandidateViewPseudonymKey + quota CardViewQuota + clock func() time.Time +} + +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Projector == nil || deps.Quota == nil || deps.Clock == nil { + return nil, fmt.Errorf("candidateview.NewService - dependencies are missing: %w", ErrCandidateViewServiceMissing) + } + if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil { + return nil, fmt.Errorf("candidateview.NewService - pseudonym key is invalid: %w", ErrCandidateViewServiceMissing) + } + return &Service{ + transactor: deps.Transactor, projector: deps.Projector, pseudonymKey: deps.PseudonymKey, quota: deps.Quota, + clock: deps.Clock, + }, nil +} + +// RateLimitedError carries only the retry time derived from the current +// organization quota; it does not include candidate or organization values. +type RateLimitedError struct{ RetryAt time.Time } + +func (err *RateLimitedError) Error() string { return ErrCandidateViewQuotaExceeded.Error() } +func (err *RateLimitedError) Unwrap() error { return ErrCandidateViewQuotaExceeded } + +// GetOrganizationCard reads a handle only from the current, locked, +// organization-visible cohort. Quota and the field-code audit commit with the +// visibility checks, so failed reads leave neither behind. +func (service *Service) GetOrganizationCard( + ctx context.Context, + actorID, organizationID uuid.UUID, + handle string, +) (domain.AnonymousCandidateViewDTO, error) { + const location = "candidateview.Service.GetOrganizationCard" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return domain.AnonymousCandidateViewDTO{}, ErrForbidden + } + if !domain.IsCandidateViewPseudonym(handle) { + return domain.AnonymousCandidateViewDTO{}, ErrInvalidCandidateHandle + } + var result domain.AnonymousCandidateViewDTO + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + view, err := service.getOrganizationCardInTransaction(ctx, unit, actorID, organizationID, handle, location) + if err != nil { + return err + } + result = view + return nil + }) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) getOrganizationCardInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + handle, location string, +) (domain.AnonymousCandidateViewDTO, error) { + organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, err + } + decision, err := service.quota(ctx, unit, organization, candidateID) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - reserve card view: %w", location, err) + } + if !decision.Allowed { + return domain.AnonymousCandidateViewDTO{}, &RateLimitedError{RetryAt: decision.RetryAt.UTC()} + } + event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, service.clock()) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build access audit: %w", location, err) + } + if err := repository.RecordCandidateCardAccess(ctx, event); err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - record access audit: %w", location, err) + } + return view, nil +} + +func (service *Service) currentOrganizationCard( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + handle, location string, +) (domain.Organization, outbound.PrivacyViewRepository, uuid.UUID, domain.AnonymousCandidateViewDTO, error) { + organization, repository, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location) + if err != nil { + return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err + } + candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location) + if err != nil { + return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err + } + view, err := projectedViewForHandle(service, organizationID, sources, handle, location) + if err != nil { + return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err + } + return organization, repository, candidateID, view, nil +} + +func loadCurrentVisibleCohort( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + location string, +) (domain.Organization, outbound.PrivacyViewRepository, []domain.CandidateViewSource, error) { + organization, err := authorizeEmployer(ctx, unit, actorID, organizationID) + if err != nil { + return domain.Organization{}, nil, nil, err + } + repository, err := privacyViewRepository(unit) + if err != nil { + return domain.Organization{}, nil, nil, err + } + sources, err := repository.ListVisibleCandidateViewSources(ctx, organizationID) + if err != nil { + return domain.Organization{}, nil, nil, fmt.Errorf("%s - read candidate cohort: %w", location, err) + } + sources, err = lockCurrentVisibleCohort(ctx, unit, repository, organizationID, sources) + if err != nil { + return domain.Organization{}, nil, nil, err + } + return organization, repository, sources, nil +} + +func candidateIDForHandle( + service *Service, + organizationID uuid.UUID, + sources []domain.CandidateViewSource, + handle, location string, +) (uuid.UUID, error) { + for _, source := range sources { + alias, err := service.sourceAlias(organizationID, source) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - derive current alias: %w", location, err) + } + if alias == handle { + return source.CandidateID(), nil + } + } + return uuid.Nil, ErrCandidateCardNotFound +} + +func projectedViewForHandle( + service *Service, + organizationID uuid.UUID, + sources []domain.CandidateViewSource, + handle, location string, +) (domain.AnonymousCandidateViewDTO, error) { + views, err := service.projector.ProjectSources(organizationID, sources) + if err != nil { + return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build current candidate view: %w", location, err) + } + for _, view := range views { + if view.Pseudonym == handle { + return view, nil + } + } + return domain.AnonymousCandidateViewDTO{}, ErrCandidateCardNotFound +} + +// PreviewResult contains only the candidate's own current publication state +// and the strict anonymous-card projection. +type PreviewResult struct { + Published bool + Fields domain.CardFieldSet + Card *domain.AnonymousCandidateViewDTO + GeneratedAt time.Time +} + +// GetMyCardPreview computes a private preview without organization cohort +// context, employer quota, or access history. +func (service *Service) GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (PreviewResult, error) { + const location = "candidateview.Service.GetMyCardPreview" + if actorID == uuid.Nil { + return PreviewResult{}, ErrForbidden + } + var result PreviewResult + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, actorID); err != nil { + return err + } + repository, err := privacyViewRepository(unit) + if err != nil { + return err + } + generatedAt := service.clock().UTC().Truncate(time.Microsecond) + if generatedAt.IsZero() { + return fmt.Errorf("%s - clock returned zero: %w", location, ErrCandidateViewServiceMissing) + } + _, consentErr := repository.LockCurrentC2ForView(ctx, actorID) + if errors.Is(consentErr, outbound.ErrCandidateC2Unavailable) { + result = PreviewResult{GeneratedAt: generatedAt} + return nil + } + if consentErr != nil { + return fmt.Errorf("%s - lock current C2: %w", location, consentErr) + } + published, err := repository.LockPublicationForPreview(ctx, actorID) + if err != nil { + return fmt.Errorf("%s - lock publication: %w", location, err) + } + if !published { + result = PreviewResult{GeneratedAt: generatedAt} + return nil + } + source, err := repository.ReadCandidateViewSourceForPreview(ctx, actorID) + if err != nil { + return fmt.Errorf("%s - read private preview source: %w", location, err) + } + card, err := service.projector.PreviewSource(source) + if err != nil { + return fmt.Errorf("%s - build private preview: %w", location, err) + } + result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, GeneratedAt: generatedAt} + return nil + }) + if err != nil { + return PreviewResult{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// ListMyCardAccessHistory returns one owner-scoped history page. +func (service *Service) ListMyCardAccessHistory( + ctx context.Context, + command outbound.CandidateCardAccessListQuery, +) (outbound.CandidateCardAccessListPage, error) { + const location = "candidateview.Service.ListMyCardAccessHistory" + if command.CandidateID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxCandidateCardAccessPageSize { + return outbound.CandidateCardAccessListPage{}, domain.ErrInvalidCandidateCardAccess + } + var result outbound.CandidateCardAccessListPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, command.CandidateID); err != nil { + return err + } + repository, err := privacyViewRepository(unit) + if err != nil { + return err + } + result, err = repository.ListCandidateCardAccess(ctx, command) + if err != nil { + return fmt.Errorf("%s - read owner access history: %w", location, err) + } + return nil + }) + if err != nil { + return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// CurrentContactFields returns only the current allowlisted grant fields. +// The production repository is closed until invitation grants are persisted. +// No workflow state or C4 ledger entry alone can open this read. +func (service *Service) CurrentContactFields( + ctx context.Context, + actorID, organizationID uuid.UUID, + handle string, +) (domain.ContactFieldSet, error) { + const location = "candidateview.Service.CurrentContactFields" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return domain.ContactFieldSet{}, ErrForbidden + } + if !domain.IsCandidateViewPseudonym(handle) { + return domain.ContactFieldSet{}, ErrInvalidCandidateHandle + } + var fields domain.ContactFieldSet + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, repository, candidateID, _, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location) + if err != nil { + return err + } + fields, err = repository.CurrentFields(ctx, organizationID, candidateID) + if err != nil { + return fmt.Errorf("%s - read current contact grant: %w", location, err) + } + if fields.IsZero() { + return outbound.ErrContactAccessClosed + } + event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID, + Kind: domain.CandidateCardAccessContactRead, ContactFields: fields.Fields(), OccurredAt: service.clock(), + }) + if err != nil { + return fmt.Errorf("%s - build contact access audit: %w", location, err) + } + if err := repository.RecordCandidateCardAccess(ctx, event); err != nil { + return fmt.Errorf("%s - record contact access audit: %w", location, err) + } + return nil + }) + if err != nil { + return domain.ContactFieldSet{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return fields, nil +} + +func authorizeEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (domain.Organization, error) { + user, err := unit.Users().GetByID(ctx, actorID) + if errors.Is(err, outbound.ErrUserNotFound) { + return domain.Organization{}, ErrForbidden + } + if err != nil { + return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read actor account: %w", err) + } + if !user.EmailVerified() || user.Scenario != domain.ScenarioEmployer { + return domain.Organization{}, ErrForbidden + } + if _, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID); err != nil { + if errors.Is(err, outbound.ErrOrganizationNotFound) { + return domain.Organization{}, outbound.ErrOrganizationNotFound + } + return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - lock membership: %w", err) + } + organization, _, err := unit.Organizations().GetForMember(ctx, organizationID, actorID) + if err != nil { + return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read organization: %w", err) + } + return organization, nil +} + +func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error { + user, err := unit.Users().GetByID(ctx, actorID) + if errors.Is(err, outbound.ErrUserNotFound) { + return ErrForbidden + } + if err != nil { + return fmt.Errorf("candidateview.authorizeCandidate - read actor account: %w", err) + } + if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate { + return ErrForbidden + } + return nil +} + +func privacyViewRepository(unit outbound.UnitOfWork) (outbound.PrivacyViewRepository, error) { + repository := unit.PrivacyView() + if repository == nil { + return nil, ErrCandidateViewServiceMissing + } + return repository, nil +} + +func lockCurrentVisibleCohort( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.PrivacyViewRepository, + organizationID uuid.UUID, + sources []domain.CandidateViewSource, +) ([]domain.CandidateViewSource, error) { + checked := make(map[uuid.UUID]bool) + current := sources + for range maxCohortStabilizationPasses { + for _, source := range current { + candidateID := source.CandidateID() + if _, exists := checked[candidateID]; exists { + continue + } + visible, err := lockCandidateVisibility(ctx, unit, repository, organizationID, candidateID) + if err != nil { + return nil, err + } + checked[candidateID] = visible + } + refreshed, err := repository.ListVisibleCandidateViewSources(ctx, organizationID) + if err != nil { + return nil, fmt.Errorf("candidateview.lockCurrentVisibleCohort - re-read cohort: %w", err) + } + allLocked := true + for _, source := range refreshed { + eligible, exists := checked[source.CandidateID()] + if !exists { + allLocked = false + break + } + if !eligible { + return nil, ErrConcurrentVisibilityChange + } + } + if allLocked { + return refreshed, nil + } + current = refreshed + } + return nil, ErrConcurrentVisibilityChange +} + +func lockCandidateVisibility( + ctx context.Context, + unit outbound.UnitOfWork, + repository outbound.PrivacyViewRepository, + organizationID, candidateID uuid.UUID, +) (bool, error) { + if err := repository.LockCandidateAccountForView(ctx, candidateID); err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return false, nil + } + return false, err + } + candidate, err := unit.Users().GetByID(ctx, candidateID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return false, nil + } + return false, fmt.Errorf("candidateview.lockCandidateVisibility - read candidate account: %w", err) + } + if !candidate.EmailVerified() || candidate.Scenario != domain.ScenarioCandidate { + return false, nil + } + consentID, err := repository.LockCurrentC2ForView(ctx, candidateID) + if err != nil { + if errors.Is(err, outbound.ErrCandidateC2Unavailable) { + return false, nil + } + return false, err + } + return repository.LockVisiblePublicationForView(ctx, organizationID, candidateID, consentID) +} + +func (service *Service) sourceAlias(organizationID uuid.UUID, source domain.CandidateViewSource) (string, error) { + alias, err := service.pseudonymKey.ForOrganization(organizationID, source.CandidateID()) + if err != nil { + return "", fmt.Errorf("candidateview.Service.sourceAlias - derive candidate alias: %w", domain.ErrInvalidAnonymousCandidateView) + } + return alias, nil +} + +func cardViewAccessEvent( + candidateID, organizationID, actorID uuid.UUID, + view domain.AnonymousCandidateViewDTO, + at time.Time, +) (domain.CandidateCardAccess, error) { + var fields []domain.CardField + if len(view.Categories) > 0 { + fields = append(fields, domain.CardFieldCategories) + } + if len(view.Skills) > 0 { + fields = append(fields, domain.CardFieldStack) + } + if view.ExperienceBand != nil { + fields = append(fields, domain.CardFieldExperience) + } + if len(view.SelfAssessment) > 0 { + fields = append(fields, domain.CardFieldSelfAssessment) + } + if len(view.WorkFormats) > 0 { + fields = append(fields, domain.CardFieldWorkFormats) + } + if view.SalaryCompatibility != nil { + fields = append(fields, domain.CardFieldSalaryCompatibility) + } + if !domain.IsCandidateViewPseudonym(view.Pseudonym) { + return domain.CandidateCardAccess{}, ErrInvalidCandidateHandle + } + return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID, + Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: at, + }) +} diff --git a/backend/internal/usecase/candidateview/service_test.go b/backend/internal/usecase/candidateview/service_test.go new file mode 100644 index 0000000..444f57b --- /dev/null +++ b/backend/internal/usecase/candidateview/service_test.go @@ -0,0 +1,61 @@ +package candidateview + +import ( + "bytes" + "errors" + "slices" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func TestCardViewAccessEventRecordsOnlyFieldsReturnedInTheProjection(t *testing.T) { + t.Parallel() + + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("candidate-view-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + candidateID, organizationID, actorID := uuid.New(), uuid.New(), uuid.New() + pseudonym, err := key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + + view := domain.AnonymousCandidateViewDTO{Pseudonym: pseudonym} + event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, time.Now()) + if err != nil { + t.Fatalf("cardViewAccessEvent(pseudonym only) error = %v", err) + } + if got := event.FieldCodes(); len(got) != 0 { + t.Fatalf("pseudonym-only field codes = %v, want empty", got) + } + + band := domain.CandidateExperienceBandOneToThree + compatibility := domain.CandidateViewSalaryCompatible + view.Categories = []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}} + view.Skills = []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo} + view.ExperienceBand = &band + view.WorkFormats = []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote} + view.SalaryCompatibility = &compatibility + event, err = cardViewAccessEvent(candidateID, organizationID, actorID, view, time.Now()) + if err != nil { + t.Fatalf("cardViewAccessEvent(projected fields) error = %v", err) + } + want := []string{"categories", "experience", "salary_compatibility", "stack", "work_formats"} + if got := event.FieldCodes(); !slices.Equal(got, want) { + t.Fatalf("projected field codes = %v, want %v", got, want) + } +} + +func TestCardViewAccessEventRejectsAHandleThatIsNotAnOpaqueAlias(t *testing.T) { + t.Parallel() + + _, err := cardViewAccessEvent(uuid.New(), uuid.New(), uuid.New(), domain.AnonymousCandidateViewDTO{Pseudonym: "candidate-id"}, time.Now()) + if !errors.Is(err, ErrInvalidCandidateHandle) { + t.Fatalf("cardViewAccessEvent(invalid alias) error = %v, want ErrInvalidCandidateHandle", err) + } +} diff --git a/backend/internal/usecase/consent/service_test.go b/backend/internal/usecase/consent/service_test.go index b0c90d0..41633e3 100644 --- a/backend/internal/usecase/consent/service_test.go +++ b/backend/internal/usecase/consent/service_test.go @@ -676,6 +676,17 @@ func (ledger *fakeLedger) Current(_ context.Context, subjectID uuid.UUID, purpos return domain.ConsentRecord{}, outbound.ErrConsentNotFound } +func (ledger *fakeLedger) LockCurrentForUse( + ctx context.Context, + subjectID uuid.UUID, + purpose domain.ConsentPurpose, +) (domain.ConsentRecord, error) { + if purpose != domain.ConsentPurposeAutoCategorization { + return domain.ConsentRecord{}, domain.ErrInvalidConsent + } + return ledger.Current(ctx, subjectID, purpose) +} + func (ledger *fakeLedger) LockRegistration(_ context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) { for index := len(ledger.records) - 1; index >= 0; index-- { if record := ledger.records[index]; record.SubjectID() == subjectID && diff --git a/backend/internal/usecase/identity/keyring.go b/backend/internal/usecase/identity/keyring.go index 166b045..24f70a8 100644 --- a/backend/internal/usecase/identity/keyring.go +++ b/backend/internal/usecase/identity/keyring.go @@ -23,6 +23,7 @@ const ( labelClientBucket = "lincodex/identity/client-bucket/v1" labelTokenBucket = "lincodex/identity/verification-token-bucket/v1" labelSessionCSRF = "lincodex/identity/session-csrf/v1" + labelCandidateView = "lincodex/identity/candidate-view/v1" ) // Keyring computes the keyed digests of the anonymous identity operations: @@ -31,12 +32,13 @@ const ( // stores hold can neither confirm that an address is registered nor serve as // an offline check of a password without the server secret. type Keyring struct { - scopeKey []byte - fingerprintKey []byte - bucketKey []byte - clientKey []byte - tokenKey []byte - sessionCSRFKey []byte + scopeKey []byte + fingerprintKey []byte + bucketKey []byte + clientKey []byte + tokenKey []byte + sessionCSRFKey []byte + candidateViewKey []byte } // NewKeyring derives the purpose keys from secret. @@ -45,15 +47,29 @@ func NewKeyring(secret []byte) (*Keyring, error) { return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes) } return &Keyring{ - scopeKey: derive(secret, labelIdempotencyScope), - fingerprintKey: derive(secret, labelFingerprint), - bucketKey: derive(secret, labelEmailBucket), - clientKey: derive(secret, labelClientBucket), - tokenKey: derive(secret, labelTokenBucket), - sessionCSRFKey: derive(secret, labelSessionCSRF), + scopeKey: derive(secret, labelIdempotencyScope), + fingerprintKey: derive(secret, labelFingerprint), + bucketKey: derive(secret, labelEmailBucket), + clientKey: derive(secret, labelClientBucket), + tokenKey: derive(secret, labelTokenBucket), + sessionCSRFKey: derive(secret, labelSessionCSRF), + candidateViewKey: derive(secret, labelCandidateView), }, nil } +// CandidateViewPseudonymKey returns a purpose-specific key for anonymous +// candidate view aliases without exposing the root identity secret. +func (keyring *Keyring) CandidateViewPseudonymKey() (domain.CandidateViewPseudonymKey, error) { + if keyring == nil { + return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - keyring is nil") + } + key, err := domain.NewCandidateViewPseudonymKey(keyring.candidateViewKey) + if err != nil { + return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - derive typed key: %w", err) + } + return key, nil +} + func derive(secret []byte, label string) []byte { mac := hmac.New(sha256.New, secret) mac.Write([]byte(label)) diff --git a/backend/internal/usecase/identity/keyring_test.go b/backend/internal/usecase/identity/keyring_test.go new file mode 100644 index 0000000..e35da5a --- /dev/null +++ b/backend/internal/usecase/identity/keyring_test.go @@ -0,0 +1,56 @@ +package identity + +import ( + "bytes" + "testing" + + "github.com/google/uuid" +) + +func TestCandidateViewPseudonymKeyIsPurposeDerived(t *testing.T) { + t.Parallel() + + secret := bytes.Repeat([]byte("k"), MinKeySecretBytes) + keyring, err := NewKeyring(secret) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + + candidateID := uuid.New() + organizationID := uuid.New() + first, err := key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + preview, err := key.ForCandidatePreview(candidateID) + if err != nil { + t.Fatalf("ForCandidatePreview() error = %v", err) + } + repeated, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() repeat error = %v", err) + } + previewAgain, err := repeated.ForCandidatePreview(candidateID) + if err != nil { + t.Fatalf("ForCandidatePreview() repeat error = %v", err) + } + + if preview == first || previewAgain != preview { + t.Fatal("preview pseudonym must be stable and separate from organization pseudonyms") + } + if bytes.Contains([]byte(preview), secret) { + t.Fatal("preview pseudonym exposed the root secret") + } +} + +func TestCandidateViewPseudonymKeyRequiresValidKeyring(t *testing.T) { + t.Parallel() + + if _, err := (*Keyring)(nil).CandidateViewPseudonymKey(); err == nil { + t.Fatal("CandidateViewPseudonymKey() accepted a nil keyring") + } +} diff --git a/backend/internal/usecase/need/errors.go b/backend/internal/usecase/need/errors.go new file mode 100644 index 0000000..cab0857 --- /dev/null +++ b/backend/internal/usecase/need/errors.go @@ -0,0 +1,11 @@ +package need + +import "errors" + +var ( + ErrForbidden = errors.New("organization need operation forbidden") + ErrEmailNotVerified = errors.New("organization need requires a confirmed email") + ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request") + ErrInvalidIdempotencyKey = errors.New("invalid idempotency key") + ErrInvalidCreateRequest = errors.New("invalid organization need create request") +) diff --git a/backend/internal/usecase/need/merge.go b/backend/internal/usecase/need/merge.go new file mode 100644 index 0000000..9b01c4e --- /dev/null +++ b/backend/internal/usecase/need/merge.go @@ -0,0 +1,841 @@ +package need + +import ( + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ErrInvalidRequest = errors.New("invalid organization need request") + +// ValidationError identifies the contract field that rejected a need request. +type ValidationError struct { + Pointer string + Reason string +} + +func (validation *ValidationError) Error() string { + return fmt.Sprintf("need request field %s: %s", validation.Pointer, validation.Reason) +} + +func (validation *ValidationError) Unwrap() error { return ErrInvalidRequest } + +// Field distinguishes a missing property from a property explicitly set to null. +type Field[T any] struct { + Set bool + Null bool + Value T +} + +// Decision is an explicit value and confirmation state sent by an owner. +type Decision[T any] struct { + Value T + Status domain.NeedValueStatus +} + +type SkillInput struct { + Name string + Status domain.NeedItemStatus +} + +type TaskInput struct { + Text string + Status domain.NeedItemStatus +} + +// CreateInput preserves request presence so absent fields may use source text +// while explicit nulls and empty lists suppress extraction for that field. +type CreateInput struct { + Title string + VacancyID Field[uuid.UUID] + SourceText Field[string] + Specialization Field[Decision[domain.SpecializationCode]] + Grade Field[Decision[domain.GradeCode]] + RequiredSkills []SkillInput + DesiredSkills []SkillInput + Tasks []TaskInput + Domain Field[Decision[string]] + WorkFormats Field[Decision[[]domain.NeedWorkFormat]] + Location Field[Decision[string]] + Salary Field[Decision[domain.NeedSalaryRange]] +} + +// UpdateInput is a full replacement for every field it sets. Nil lists mean +// absent; non-nil empty lists explicitly delete all items in that list. +type UpdateInput struct { + ExpectedVersion int64 + Title Field[string] + VacancyID Field[uuid.UUID] + SourceText Field[string] + Specialization Field[Decision[domain.SpecializationCode]] + Grade Field[Decision[domain.GradeCode]] + RequiredSkills []SkillInput + DesiredSkills []SkillInput + Tasks []TaskInput + Domain Field[Decision[string]] + WorkFormats Field[Decision[[]domain.NeedWorkFormat]] + Location Field[Decision[string]] + Salary Field[Decision[domain.NeedSalaryRange]] +} + +func createNeed(input CreateInput, organizationID, needID uuid.UUID, now time.Time) (domain.Need, error) { + const location = "need.createNeed" + if organizationID == uuid.Nil || needID == uuid.Nil || now.IsZero() { + return domain.Need{}, fmt.Errorf("%s - organization, need, and application time must be set: %w", location, ErrInvalidRequest) + } + if input.VacancyID.Set && !input.VacancyID.Null { + return domain.Need{}, invalidRequest("/vacancy_id", "vacancies are not available") + } + sourceText, sourceProvided, err := createSourceText(input.SourceText) + if err != nil { + return domain.Need{}, err + } + requirements, err := createNeedRequirements(input, sourceText, sourceProvided) + if err != nil { + return domain.Need{}, err + } + snapshot := domain.NeedSnapshot{ + ID: needID, OrganizationID: organizationID, Title: input.Title, + SourceText: sourceText, Version: 1, RequirementsVersion: 1, + Requirements: requirements, RejectedSuggestions: []domain.NeedRejectedSuggestion{}, + CreatedAt: now, UpdatedAt: now, + } + created, err := domain.NewNeed(snapshot) + if err != nil { + return domain.Need{}, mapDomainValidation(err) + } + return created, nil +} + +func createNeedRequirements(input CreateInput, sourceText *string, sourceProvided bool) (domain.NeedRequirements, error) { + requirements := domain.EmptyNeedRequirements() + if sourceProvided { + requirements = parseSourceText(*sourceText, 1) + } + if err := applyCreateScalars(&requirements, input); err != nil { + return domain.NeedRequirements{}, err + } + if input.RequiredSkills != nil { + created, err := createSkills(input.RequiredSkills, "/required_skills") + if err != nil { + return domain.NeedRequirements{}, err + } + requirements.RequiredSkills = created + } + if input.DesiredSkills != nil { + created, err := createSkills(input.DesiredSkills, "/desired_skills") + if err != nil { + return domain.NeedRequirements{}, err + } + requirements.DesiredSkills = created + } + if input.Tasks != nil { + created, err := createTasks(input.Tasks, "/tasks") + if err != nil { + return domain.NeedRequirements{}, err + } + requirements.Tasks = created + } + removeExtractedSkillsShadowedByConfirmed(&requirements) + if err := validateSkillUniqueness(requirements); err != nil { + return domain.NeedRequirements{}, err + } + return requirements, nil +} + +func createSourceText(field Field[string]) (*string, bool, error) { + if !field.Set || field.Null { + return nil, false, nil + } + if field.Value == "" { + return nil, false, invalidRequest("/source_text", "must contain text or be null") + } + value := field.Value + return &value, true, nil +} + +func applyCreateScalars(requirements *domain.NeedRequirements, input CreateInput) error { + var err error + if requirements.Specialization, err = createScalar(input.Specialization, requirements.Specialization, "/specialization"); err != nil { + return err + } + if requirements.Grade, err = createScalar(input.Grade, requirements.Grade, "/grade"); err != nil { + return err + } + if requirements.Domain, err = createScalar(input.Domain, requirements.Domain, "/domain"); err != nil { + return err + } + if requirements.WorkFormats, err = createScalar(input.WorkFormats, requirements.WorkFormats, "/work_formats"); err != nil { + return err + } + if requirements.Location, err = createScalar(input.Location, requirements.Location, "/location"); err != nil { + return err + } + if requirements.Salary, err = createScalar(input.Salary, requirements.Salary, "/salary"); err != nil { + return err + } + return nil +} + +func createScalar[T any](field Field[Decision[T]], parsed domain.NeedValue[T], pointer string) (domain.NeedValue[T], error) { + if !field.Set { + return parsed, nil + } + if field.Null { + return unknownNeedValue[T](), nil + } + if field.Value.Status != domain.NeedValueConfirmed { + return domain.NeedValue[T]{}, invalidRequest(pointer+"/status", "a new need requires confirmed values") + } + return confirmedNeedValue(field.Value.Value, manualNeedSource()), nil +} + +func createSkills(inputs []SkillInput, pointer string) ([]domain.NeedSkill, error) { + result := make([]domain.NeedSkill, 0, len(inputs)) + for index, input := range inputs { + itemPointer := fmt.Sprintf("%s/%d", pointer, index) + if input.Status != domain.NeedItemConfirmed { + return nil, invalidRequest(itemPointer+"/status", "a new need requires confirmed items") + } + result = append(result, domain.NeedSkill{ + Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed, + Source: *manualNeedSource(), + }) + } + return result, nil +} + +func createTasks(inputs []TaskInput, pointer string) ([]domain.NeedTask, error) { + result := make([]domain.NeedTask, 0, len(inputs)) + for index, input := range inputs { + if input.Status != domain.NeedItemConfirmed { + return nil, invalidRequest(fmt.Sprintf("%s/%d/status", pointer, index), "a new need requires confirmed items") + } + result = append(result, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()}) + } + return result, nil +} + +func reviseNeed(current domain.Need, input UpdateInput, now time.Time) (domain.Need, bool, error) { + const location = "need.reviseNeed" + if current.IsZero() || now.IsZero() { + return domain.Need{}, false, fmt.Errorf("%s - current need and application time must be set: %w", location, ErrInvalidRequest) + } + if input.ExpectedVersion < 1 { + return domain.Need{}, false, invalidRequest("/expected_version", "must be positive") + } + snapshot := current.Snapshot() + if err := applyNeedUpdate(current, &snapshot, input); err != nil { + return domain.Need{}, false, err + } + snapshot.UpdatedAt = now + return current.Revise(input.ExpectedVersion, snapshot) +} + +func applyNeedUpdate(current domain.Need, snapshot *domain.NeedSnapshot, input UpdateInput) error { + if input.Title.Set { + if input.Title.Null { + return stalePatchError(current, input.ExpectedVersion, invalidRequest("/title", "cannot be null")) + } + snapshot.Title = input.Title.Value + } + if input.VacancyID.Set { + if !input.VacancyID.Null { + return stalePatchError(current, input.ExpectedVersion, invalidRequest("/vacancy_id", "vacancies are not available")) + } + snapshot.VacancyID = nil + } + newSourceText, sourceChanged, sourceErr := updateSourceText(input.SourceText, snapshot.SourceText) + if sourceErr != nil { + return stalePatchError(current, input.ExpectedVersion, sourceErr) + } + snapshot.SourceText = newSourceText + requirements := snapshot.Requirements + if err := applyExplicitScalars(snapshot, &requirements, input); err != nil { + return stalePatchError(current, input.ExpectedVersion, err) + } + if err := applyExplicitLists(snapshot, &requirements, input); err != nil { + return stalePatchError(current, input.ExpectedVersion, err) + } + if sourceChanged { + parsed := parseSourceText(*snapshot.SourceText, current.Version()+1) + reparseScalars(snapshot, &requirements, parsed, input) + reparseLists(snapshot, &requirements, parsed, current.Snapshot().Requirements, input) + } + if err := validateSkillUniqueness(requirements); err != nil { + return stalePatchError(current, input.ExpectedVersion, err) + } + snapshot.Requirements = requirements + return nil +} + +func stalePatchError(current domain.Need, expectedVersion int64, err error) error { + if expectedVersion != current.Version() { + return domain.ErrNeedVersionConflict + } + return err +} + +func updateSourceText(field Field[string], current *string) (*string, bool, error) { + if !field.Set { + return cloneString(current), false, nil + } + if field.Null { + return nil, false, nil + } + if field.Value == "" { + return nil, false, invalidRequest("/source_text", "must contain text or be null") + } + value := field.Value + changed := current == nil || *current != value + return &value, changed, nil +} + +func applyExplicitScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error { + if err := applyScalarPatch(snapshot, &requirements.Specialization, input.Specialization, domain.NeedRejectedSpecialization, "/specialization", scalarString[domain.SpecializationCode]); err != nil { + return err + } + if err := applyScalarPatch(snapshot, &requirements.Grade, input.Grade, domain.NeedRejectedGrade, "/grade", scalarString[domain.GradeCode]); err != nil { + return err + } + if err := applyScalarPatch(snapshot, &requirements.Domain, input.Domain, domain.NeedRejectedDomain, "/domain", scalarString[string]); err != nil { + return err + } + if err := applyScalarPatch(snapshot, &requirements.WorkFormats, input.WorkFormats, domain.NeedRejectedWorkFormats, "/work_formats", scalarWorkFormats); err != nil { + return err + } + if err := applyScalarPatch(snapshot, &requirements.Location, input.Location, domain.NeedRejectedLocation, "/location", scalarString[string]); err != nil { + return err + } + if err := applyScalarPatch(snapshot, &requirements.Salary, input.Salary, domain.NeedRejectedSalary, "/salary", scalarSalary); err != nil { + return err + } + return nil +} + +func applyScalarPatch[T any]( + snapshot *domain.NeedSnapshot, + current *domain.NeedValue[T], + field Field[Decision[T]], + rejectedField domain.NeedRejectedSuggestionField, + pointer string, + canonical func(T) []string, +) error { + if !field.Set { + return nil + } + if field.Null { + if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil { + return err + } + *current = unknownNeedValue[T]() + return nil + } + decision := field.Value + switch decision.Status { + case domain.NeedValueUnknown: + return invalidRequest(pointer+"/status", "must be confirmed or extracted") + case domain.NeedValueExtracted: + if current.Status != domain.NeedValueExtracted || current.Value == nil || !reflect.DeepEqual(*current.Value, decision.Value) { + return invalidRequest(pointer+"/status", "extracted is allowed only for the stored suggestion") + } + return nil + case domain.NeedValueConfirmed: + if current.Value != nil && reflect.DeepEqual(*current.Value, decision.Value) { + current.Status = domain.NeedValueConfirmed + return nil + } + if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil { + return err + } + *current = confirmedNeedValue(decision.Value, manualNeedSource()) + return nil + default: + return invalidRequest(pointer+"/status", "must be confirmed or extracted") + } +} + +func rejectExtractedScalar[T any]( + snapshot *domain.NeedSnapshot, + field domain.NeedRejectedSuggestionField, + value domain.NeedValue[T], + canonical func(T) []string, + pointer string, +) error { + if value.Status != domain.NeedValueExtracted || value.Value == nil { + return nil + } + for _, candidate := range canonical(*value.Value) { + if err := addRejectedSuggestion(snapshot, field, candidate, pointer); err != nil { + return err + } + } + return nil +} + +func reparseScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, parsed domain.NeedRequirements, input UpdateInput) { + if !input.Specialization.Set && requirements.Specialization.Status != domain.NeedValueConfirmed { + requirements.Specialization = filterRejectedScalar(snapshot, domain.NeedRejectedSpecialization, parsed.Specialization, scalarString[domain.SpecializationCode]) + } + if !input.Grade.Set && requirements.Grade.Status != domain.NeedValueConfirmed { + requirements.Grade = filterRejectedScalar(snapshot, domain.NeedRejectedGrade, parsed.Grade, scalarString[domain.GradeCode]) + } + if !input.Domain.Set && requirements.Domain.Status != domain.NeedValueConfirmed { + requirements.Domain = filterRejectedScalar(snapshot, domain.NeedRejectedDomain, parsed.Domain, scalarString[string]) + } + if !input.WorkFormats.Set && requirements.WorkFormats.Status != domain.NeedValueConfirmed { + requirements.WorkFormats = filterRejectedWorkFormats(snapshot, parsed.WorkFormats) + } + if !input.Location.Set && requirements.Location.Status != domain.NeedValueConfirmed { + requirements.Location = filterRejectedScalar(snapshot, domain.NeedRejectedLocation, parsed.Location, scalarString[string]) + } + if !input.Salary.Set && requirements.Salary.Status != domain.NeedValueConfirmed { + requirements.Salary = filterRejectedScalar(snapshot, domain.NeedRejectedSalary, parsed.Salary, scalarSalary) + } +} + +func filterRejectedWorkFormats(snapshot *domain.NeedSnapshot, value domain.NeedValue[[]domain.NeedWorkFormat]) domain.NeedValue[[]domain.NeedWorkFormat] { + if value.Status != domain.NeedValueExtracted || value.Value == nil { + return value + } + filtered := make([]domain.NeedWorkFormat, 0, len(*value.Value)) + for _, format := range *value.Value { + if !isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedWorkFormats, string(format)) { + filtered = append(filtered, format) + } + } + if len(filtered) == 0 { + return unknownNeedValue[[]domain.NeedWorkFormat]() + } + value.Value = &filtered + return value +} + +func filterRejectedScalar[T any]( + snapshot *domain.NeedSnapshot, + field domain.NeedRejectedSuggestionField, + value domain.NeedValue[T], + canonical func(T) []string, +) domain.NeedValue[T] { + if value.Status != domain.NeedValueExtracted || value.Value == nil { + return value + } + for _, candidate := range canonical(*value.Value) { + if isRejected(snapshot.RejectedSuggestions, field, candidate) { + return unknownNeedValue[T]() + } + } + return value +} + +func applyExplicitLists(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error { + if err := rejectRemovedSkillSuggestions(snapshot, *requirements, input); err != nil { + return err + } + oldSkills := append(append([]domain.NeedSkill(nil), requirements.RequiredSkills...), requirements.DesiredSkills...) + if err := replaceExplicitSkillList(&requirements.RequiredSkills, input.RequiredSkills, oldSkills, "/required_skills"); err != nil { + return err + } + if err := replaceExplicitSkillList(&requirements.DesiredSkills, input.DesiredSkills, oldSkills, "/desired_skills"); err != nil { + return err + } + return replaceExplicitTaskList(snapshot, requirements, input.Tasks) +} + +func rejectRemovedSkillSuggestions(snapshot *domain.NeedSnapshot, requirements domain.NeedRequirements, input UpdateInput) error { + if input.RequiredSkills == nil && input.DesiredSkills == nil { + return nil + } + requested := append(append([]SkillInput(nil), input.RequiredSkills...), input.DesiredSkills...) + groups := []struct { + items []domain.NeedSkill + present bool + pointer string + }{ + {items: requirements.RequiredSkills, present: input.RequiredSkills != nil, pointer: "/required_skills"}, + {items: requirements.DesiredSkills, present: input.DesiredSkills != nil, pointer: "/desired_skills"}, + } + for _, group := range groups { + for _, old := range group.items { + if !group.present || old.Status != domain.NeedItemExtracted || skillInputIndex(requested, old.Name) >= 0 { + continue + } + if err := addRejectedSuggestion(snapshot, domain.NeedRejectedSkills, old.Name, group.pointer); err != nil { + return err + } + } + } + return nil +} + +func replaceExplicitSkillList(target *[]domain.NeedSkill, inputs []SkillInput, old []domain.NeedSkill, pointer string) error { + if inputs == nil { + return nil + } + updated, err := replaceSkills(inputs, old, pointer) + if err != nil { + return err + } + *target = updated + return nil +} + +func replaceExplicitTaskList(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, inputs []TaskInput) error { + if inputs == nil { + return nil + } + for _, old := range requirements.Tasks { + if old.Status != domain.NeedItemExtracted || taskInputIndex(inputs, old.Text) >= 0 { + continue + } + if err := addRejectedSuggestion(snapshot, domain.NeedRejectedTasks, old.Text, "/tasks"); err != nil { + return err + } + } + updated, err := replaceTasks(inputs, requirements.Tasks) + if err != nil { + return err + } + requirements.Tasks = updated + return nil +} + +func removeExtractedSkillsShadowedByConfirmed(requirements *domain.NeedRequirements) { + confirmed := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills) + filter := func(skills []domain.NeedSkill) []domain.NeedSkill { + result := make([]domain.NeedSkill, 0, len(skills)) + for _, skill := range skills { + if skill.Status == domain.NeedItemExtracted { + if _, exists := confirmed[canonicalNeedKey(skill.Name)]; exists { + continue + } + } + result = append(result, skill) + } + return result + } + requirements.RequiredSkills = filter(requirements.RequiredSkills) + requirements.DesiredSkills = filter(requirements.DesiredSkills) +} + +func replaceSkills(inputs []SkillInput, old []domain.NeedSkill, pointer string) ([]domain.NeedSkill, error) { + updated := make([]domain.NeedSkill, 0, len(inputs)) + seen := make(map[string]struct{}, len(inputs)) + for index, input := range inputs { + itemPointer := fmt.Sprintf("%s/%d", pointer, index) + key := canonicalNeedKey(input.Name) + if _, exists := seen[key]; exists { + return nil, invalidRequest(itemPointer+"/name", "duplicates a skill in this request") + } + seen[key] = struct{}{} + previous, exists := findSkill(old, key) + switch input.Status { + case domain.NeedItemExtracted: + if !exists || previous.Status != domain.NeedItemExtracted { + return nil, invalidRequest(itemPointer+"/status", "extracted is allowed only for a stored suggestion") + } + updated = append(updated, previous) + case domain.NeedItemConfirmed: + if exists { + previous.Status = domain.NeedItemConfirmed + updated = append(updated, previous) + continue + } + updated = append(updated, domain.NeedSkill{ + Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed, + Source: *manualNeedSource(), + }) + default: + return nil, invalidRequest(itemPointer+"/status", "must be confirmed or extracted") + } + } + return updated, nil +} + +func replaceTasks(inputs []TaskInput, old []domain.NeedTask) ([]domain.NeedTask, error) { + updated := make([]domain.NeedTask, 0, len(inputs)) + seen := make(map[string]struct{}, len(inputs)) + for index, input := range inputs { + pointer := fmt.Sprintf("/tasks/%d", index) + key := canonicalNeedKey(input.Text) + if _, exists := seen[key]; exists { + return nil, invalidRequest(pointer+"/text", "duplicates a task in this request") + } + seen[key] = struct{}{} + previous, exists := findTask(old, input.Text) + switch input.Status { + case domain.NeedItemExtracted: + if !exists || previous.Status != domain.NeedItemExtracted { + return nil, invalidRequest(pointer+"/status", "extracted is allowed only for a stored suggestion") + } + updated = append(updated, previous) + case domain.NeedItemConfirmed: + if exists { + previous.Status = domain.NeedItemConfirmed + updated = append(updated, previous) + continue + } + updated = append(updated, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()}) + default: + return nil, invalidRequest(pointer+"/status", "must be confirmed or extracted") + } + } + return updated, nil +} + +func reparseLists( + snapshot *domain.NeedSnapshot, + requirements *domain.NeedRequirements, + parsed domain.NeedRequirements, + previous domain.NeedRequirements, + input UpdateInput, +) { + if input.RequiredSkills != nil || input.DesiredSkills != nil { + blocked := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills) + if input.RequiredSkills != nil { + addSkillNames(blocked, requirements.RequiredSkills) + } + if input.DesiredSkills != nil { + addSkillNames(blocked, requirements.DesiredSkills) + } + if input.RequiredSkills == nil { + requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked) + addSkillNames(blocked, requirements.RequiredSkills) + } + if input.DesiredSkills == nil { + requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked) + } + } else { + blocked := confirmedSkillNames(previous.RequiredSkills, previous.DesiredSkills) + requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked) + addSkillNames(blocked, requirements.RequiredSkills) + requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked) + } + if input.Tasks == nil { + requirements.Tasks = reparseTasks(snapshot, previous.Tasks, parsed.Tasks) + } +} + +func reparseSkills( + snapshot *domain.NeedSnapshot, + previous, parsed []domain.NeedSkill, + blocked map[string]struct{}, +) []domain.NeedSkill { + result := make([]domain.NeedSkill, 0, len(previous)+len(parsed)) + seen := make(map[string]struct{}, len(previous)+len(parsed)) + for _, skill := range previous { + if skill.Status != domain.NeedItemConfirmed { + continue + } + key := canonicalNeedKey(skill.Name) + result = append(result, skill) + seen[key] = struct{}{} + } + for _, skill := range parsed { + key := canonicalNeedKey(skill.Name) + if _, exists := seen[key]; exists { + continue + } + if _, exists := blocked[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedSkills, skill.Name) { + continue + } + result = append(result, skill) + seen[key] = struct{}{} + } + return result +} + +func reparseTasks(snapshot *domain.NeedSnapshot, previous, parsed []domain.NeedTask) []domain.NeedTask { + result := make([]domain.NeedTask, 0, len(previous)+len(parsed)) + seen := make(map[string]struct{}, len(previous)+len(parsed)) + for _, task := range previous { + if task.Status != domain.NeedItemConfirmed { + continue + } + key := canonicalNeedKey(task.Text) + result = append(result, task) + seen[key] = struct{}{} + } + for _, task := range parsed { + key := canonicalNeedKey(task.Text) + if _, exists := seen[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedTasks, task.Text) { + continue + } + result = append(result, task) + seen[key] = struct{}{} + } + return result +} + +func skillInputIndex(inputs []SkillInput, name string) int { + key := canonicalNeedKey(name) + for index, input := range inputs { + if canonicalNeedKey(input.Name) == key { + return index + } + } + return -1 +} + +func taskInputIndex(inputs []TaskInput, text string) int { + key := canonicalNeedKey(text) + for index, input := range inputs { + if canonicalNeedKey(input.Text) == key { + return index + } + } + return -1 +} + +func findSkill(skills []domain.NeedSkill, key string) (domain.NeedSkill, bool) { + for _, skill := range skills { + if canonicalNeedKey(skill.Name) == key { + return skill, true + } + } + return domain.NeedSkill{}, false +} + +func findTask(tasks []domain.NeedTask, text string) (domain.NeedTask, bool) { + for _, task := range tasks { + if task.Text == text { + return task, true + } + } + return domain.NeedTask{}, false +} + +func confirmedSkillNames(groups ...[]domain.NeedSkill) map[string]struct{} { + result := make(map[string]struct{}) + for _, group := range groups { + for _, skill := range group { + if skill.Status == domain.NeedItemConfirmed { + result[canonicalNeedKey(skill.Name)] = struct{}{} + } + } + } + return result +} + +func addSkillNames(names map[string]struct{}, skills []domain.NeedSkill) { + for _, skill := range skills { + names[canonicalNeedKey(skill.Name)] = struct{}{} + } +} + +func validateSkillUniqueness(requirements domain.NeedRequirements) error { + seen := make(map[string]struct{}, len(requirements.RequiredSkills)+len(requirements.DesiredSkills)) + for _, skill := range requirements.RequiredSkills { + seen[canonicalNeedKey(skill.Name)] = struct{}{} + } + for index, skill := range requirements.DesiredSkills { + key := canonicalNeedKey(skill.Name) + if _, exists := seen[key]; exists { + return invalidRequest(fmt.Sprintf("/desired_skills/%d/name", index), "duplicates a skill in required_skills") + } + seen[key] = struct{}{} + } + return nil +} + +func addRejectedSuggestion(snapshot *domain.NeedSnapshot, field domain.NeedRejectedSuggestionField, value, pointer string) error { + canonical := canonicalRejectedValue(field, value) + if canonical == "" || isRejected(snapshot.RejectedSuggestions, field, canonical) { + return nil + } + if len(snapshot.RejectedSuggestions) >= domain.MaxNeedRejectedSuggestions { + return invalidRequest(pointer, "too many rejected suggestions") + } + snapshot.RejectedSuggestions = append(snapshot.RejectedSuggestions, domain.NeedRejectedSuggestion{Field: field, Value: canonical}) + return nil +} + +func isRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool { + canonical := canonicalRejectedValue(field, value) + for _, suggestion := range suggestions { + if suggestion.Field == field && suggestion.Value == canonical { + return true + } + } + return false +} + +func canonicalRejectedValue(_ domain.NeedRejectedSuggestionField, value string) string { + return canonicalNeedKey(value) +} + +func canonicalNeedKey(value string) string { + return strings.ToLower(strings.Join(strings.Fields(value), " ")) +} + +func scalarString[T ~string](value T) []string { return []string{string(value)} } + +func scalarWorkFormats(value []domain.NeedWorkFormat) []string { + result := make([]string, 0, len(value)) + for _, format := range value { + result = append(result, string(format)) + } + return result +} + +func scalarSalary(value domain.NeedSalaryRange) []string { + encoded, err := json.Marshal(value) + if err != nil { + return nil + } + return []string{string(encoded)} +} + +func taxonomyForSkillName(name string) *string { + key := canonicalNeedKey(name) + for _, rule := range needSkillRules { + if strings.EqualFold(rule.name, key) && rule.taxonomy != "" { + value := rule.taxonomy + return &value + } + } + return nil +} + +func unknownNeedValue[T any]() domain.NeedValue[T] { + return domain.NeedValue[T]{Status: domain.NeedValueUnknown} +} + +func confirmedNeedValue[T any](value T, source *domain.NeedValueSource) domain.NeedValue[T] { + return domain.NeedValue[T]{Status: domain.NeedValueConfirmed, Value: &value, Source: source} +} + +func manualNeedSource() *domain.NeedValueSource { + return &domain.NeedValueSource{Origin: domain.NeedValueManual} +} + +func cloneString(value *string) *string { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +func invalidRequest(pointer, reason string) error { + return &ValidationError{Pointer: pointer, Reason: reason} +} + +func mapDomainValidation(err error) error { + if errors.Is(err, domain.ErrInvalidNeed) { + pointer := "" + if message := err.Error(); strings.Contains(message, "invalid need field ") { + field := strings.SplitN(strings.SplitN(message, "invalid need field ", 2)[1], " ", 2)[0] + pointer = field + } + return &ValidationError{Pointer: pointer, Reason: "value does not satisfy the need contract"} + } + return err +} diff --git a/backend/internal/usecase/need/merge_test.go b/backend/internal/usecase/need/merge_test.go new file mode 100644 index 0000000..41ebe8e --- /dev/null +++ b/backend/internal/usecase/need/merge_test.go @@ -0,0 +1,271 @@ +package need + +import ( + "errors" + "reflect" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func TestCreateNeedUsesOnlyExplicitValuesAndSourceSuggestions(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + created := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."}, + Grade: Field[Decision[domain.GradeCode]]{Set: true, Null: true}, + DesiredSkills: []SkillInput{}, + }, now) + requirements := created.Snapshot().Requirements + if requirements.Specialization.Status != domain.NeedValueExtracted || requirements.Specialization.Value == nil || *requirements.Specialization.Value != domain.SpecializationBackend { + t.Fatalf("specialization = %+v, want extracted backend", requirements.Specialization) + } + if requirements.Grade.Status != domain.NeedValueUnknown { + t.Fatalf("grade = %+v, want explicitly unknown", requirements.Grade) + } + if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != "Go" || requirements.RequiredSkills[1].Name != "PostgreSQL" { + t.Fatalf("required skills = %+v, want Go and PostgreSQL suggestions", requirements.RequiredSkills) + } + if requirements.DesiredSkills == nil || len(requirements.DesiredSkills) != 0 { + t.Fatalf("desired skills = %#v, want explicitly empty", requirements.DesiredSkills) + } + if created.Version() != 1 || created.RequirementsVersion() != 1 || !created.CreatedAt().Equal(now) { + t.Fatalf("created version/timestamp = %d/%d/%s", created.Version(), created.RequirementsVersion(), created.CreatedAt()) + } + + manual := mustCreateNeed(t, CreateInput{ + Title: "Go engineer", + Specialization: Field[Decision[domain.SpecializationCode]]{ + Set: true, Value: Decision[domain.SpecializationCode]{Value: domain.SpecializationBackend, Status: domain.NeedValueConfirmed}, + }, + RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}}, + }, now) + manualRequirements := manual.Snapshot().Requirements + if manualRequirements.Specialization.Status != domain.NeedValueConfirmed || manualRequirements.Grade.Status != domain.NeedValueUnknown || + len(manualRequirements.RequiredSkills) != 1 || manualRequirements.RequiredSkills[0].Source.Origin != domain.NeedValueManual { + t.Fatalf("manual requirements = %+v, want only supplied confirmed values", manualRequirements) + } +} + +func TestUpdateConfirmsAndMovesStoredSuggestionWithoutLosingProvenance(t *testing.T) { + current := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."}, + }, testNeedTime()) + before := current.Snapshot().Requirements + if len(before.RequiredSkills) != 2 || len(before.DesiredSkills) != 1 { + t.Fatalf("parsed lists = %v / %v", before.RequiredSkills, before.DesiredSkills) + } + goSource := before.RequiredSkills[0].Source + updated, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + RequiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemExtracted}}, + DesiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "Kafka", Status: domain.NeedItemExtracted}}, + }, testNeedTime().Add(time.Second)) + if err != nil { + t.Fatalf("reviseNeed() error = %v", err) + } + if !changed || updated.Version() != 2 || updated.RequirementsVersion() != 2 { + t.Fatalf("updated version/change = %d/%d/%v, want 2/2/true", updated.Version(), updated.RequirementsVersion(), changed) + } + got := updated.Snapshot().Requirements + if len(got.RequiredSkills) != 1 || got.RequiredSkills[0].Name != "PostgreSQL" || len(got.DesiredSkills) != 2 { + t.Fatalf("updated skill lists = %v / %v", got.RequiredSkills, got.DesiredSkills) + } + confirmedGo := got.DesiredSkills[0] + if confirmedGo.Name != "Go" || confirmedGo.Status != domain.NeedItemConfirmed || confirmedGo.Source.Origin != domain.NeedValueExtractedFromText || !reflect.DeepEqual(confirmedGo.Source, goSource) { + t.Fatalf("confirmed Go = %+v, want original extracted provenance", confirmedGo) + } +} + +func TestSourceEditReextractsSuggestionsButKeepsConfirmedValues(t *testing.T) { + current := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL."}, + }, testNeedTime()) + current, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "PostgreSQL", Status: domain.NeedItemExtracted}}, + }, testNeedTime().Add(time.Second)) + if err != nil || !changed { + t.Fatalf("confirm first skill: changed=%v error=%v", changed, err) + } + confirmed := current.Snapshot().Requirements.RequiredSkills[0] + updated, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 2, + SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, Kafka."}, + }, testNeedTime().Add(2*time.Second)) + if err != nil || !changed { + t.Fatalf("change source: changed=%v error=%v", changed, err) + } + requirements := updated.Snapshot().Requirements + if updated.RequirementsVersion() != current.RequirementsVersion() { + t.Fatalf("requirements_version = %d, want unchanged %d", updated.RequirementsVersion(), current.RequirementsVersion()) + } + if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != confirmed.Name || requirements.RequiredSkills[0].Status != domain.NeedItemConfirmed || !reflect.DeepEqual(requirements.RequiredSkills[0].Source, confirmed.Source) { + t.Fatalf("confirmed skill after source edit = %+v", requirements.RequiredSkills) + } + if requirements.RequiredSkills[1].Name != "Kafka" || requirements.RequiredSkills[1].Status != domain.NeedItemExtracted { + t.Fatalf("reparsed suggestions = %+v, want Kafka only after confirmed Go", requirements.RequiredSkills) + } +} + +func TestDeletedSkillSuggestionStaysSuppressedAcrossListsAndManualReadd(t *testing.T) { + current := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Желательно: PostgreSQL."}, + }, testNeedTime()) + deleted, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + DesiredSkills: []SkillInput{}, + }, testNeedTime().Add(time.Second)) + if err != nil || !changed { + t.Fatalf("delete extracted skill: changed=%v error=%v", changed, err) + } + if !hasRejected(deleted.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "POSTGRESQL") { + t.Fatalf("deleted skill suppression = %+v, want case-insensitive common skill key", deleted.Snapshot().RejectedSuggestions) + } + + manual, changed, err := reviseNeed(deleted, UpdateInput{ + ExpectedVersion: 2, + DesiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemConfirmed}}, + }, testNeedTime().Add(2*time.Second)) + if err != nil || !changed { + t.Fatalf("manual readd: changed=%v error=%v", changed, err) + } + if len(manual.Snapshot().Requirements.DesiredSkills) != 1 || manual.Snapshot().Requirements.DesiredSkills[0].Source.Origin != domain.NeedValueManual { + t.Fatalf("manual readd = %+v, want confirmed manual skill", manual.Snapshot().Requirements.DesiredSkills) + } + if !hasRejected(manual.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") { + t.Fatalf("manual readd cleared old rejection: %+v", manual.Snapshot().RejectedSuggestions) + } + + deletedAgain, changed, err := reviseNeed(manual, UpdateInput{ + ExpectedVersion: 3, + DesiredSkills: []SkillInput{}, + }, testNeedTime().Add(3*time.Second)) + if err != nil || !changed { + t.Fatalf("delete manual readd: changed=%v error=%v", changed, err) + } + updated, changed, err := reviseNeed(deletedAgain, UpdateInput{ + ExpectedVersion: 4, + SourceText: Field[string]{Set: true, Value: "Обязательно: PostgreSQL."}, + }, testNeedTime().Add(4*time.Second)) + if err != nil || !changed { + t.Fatalf("change source after readd removal: changed=%v error=%v", changed, err) + } + final := updated.Snapshot() + if len(final.Requirements.RequiredSkills) != 0 || len(final.Requirements.DesiredSkills) != 0 || !hasRejected(final.RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") { + t.Fatalf("suppressed skill returned after source edit: %+v", final.Requirements) + } +} + +func TestDeletedScalarSuggestionStaysSuppressedAfterSourceEdit(t *testing.T) { + current := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Ищем backend developer."}, + }, testNeedTime()) + deleted, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + Specialization: Field[Decision[domain.SpecializationCode]]{Set: true, Null: true}, + }, testNeedTime().Add(time.Second)) + if err != nil || !changed { + t.Fatalf("delete specialization: changed=%v error=%v", changed, err) + } + updated, changed, err := reviseNeed(deleted, UpdateInput{ + ExpectedVersion: 2, + SourceText: Field[string]{Set: true, Value: "Ищем backend developer снова."}, + }, testNeedTime().Add(2*time.Second)) + if err != nil || !changed { + t.Fatalf("change source: changed=%v error=%v", changed, err) + } + if got := updated.Snapshot(); got.Requirements.Specialization.Status != domain.NeedValueUnknown || !hasRejected(got.RejectedSuggestions, domain.NeedRejectedSpecialization, "BACKEND") { + t.Fatalf("specialization was proposed again: %+v", got) + } +} + +func TestSourceNullKeepsEveryRequirementAndSourceOnlyEditKeepsRequirementsVersion(t *testing.T) { + current := mustCreateNeed(t, CreateInput{ + Title: "Backend engineer", + SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go."}, + }, testNeedTime()) + cleared, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + SourceText: Field[string]{Set: true, Null: true}, + }, testNeedTime().Add(time.Second)) + if err != nil || !changed { + t.Fatalf("clear source text: changed=%v error=%v", changed, err) + } + if cleared.Snapshot().SourceText != nil || !reflect.DeepEqual(cleared.Snapshot().Requirements, current.Snapshot().Requirements) || cleared.RequirementsVersion() != current.RequirementsVersion() { + t.Fatalf("cleared source changed requirements: %+v", cleared.Snapshot()) + } +} + +func TestStalePatchReturnsNoopBeforeConflictAndConflictBeforeDomainError(t *testing.T) { + current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime()) + current, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"}, + }, testNeedTime().Add(time.Second)) + if err != nil || !changed { + t.Fatalf("initial title edit: changed=%v error=%v", changed, err) + } + noOp, changed, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"}, + }, testNeedTime().Add(2*time.Second)) + if err != nil || changed || noOp.Version() != current.Version() { + t.Fatalf("stale no-op: version=%d changed=%v error=%v", noOp.Version(), changed, err) + } + _, _, err = reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}}, + }, testNeedTime().Add(2*time.Second)) + if !errors.Is(err, domain.ErrNeedVersionConflict) { + t.Fatalf("stale invalid patch error = %v, want version conflict", err) + } +} + +func TestPatchRejectsExtractedValueNotStoredAsSuggestion(t *testing.T) { + current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime()) + _, _, err := reviseNeed(current, UpdateInput{ + ExpectedVersion: 1, + Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}}, + }, testNeedTime().Add(time.Second)) + var validation *ValidationError + if !errors.As(err, &validation) || validation.Pointer != "/grade/status" { + t.Fatalf("invalid extracted grade error = %v, want /grade/status validation", err) + } +} + +func mustCreateNeed(t *testing.T, input CreateInput, now time.Time) domain.Need { + t.Helper() + needID, err := uuid.NewV7() + if err != nil { + t.Fatalf("generate need ID: %v", err) + } + organizationID, err := uuid.NewV7() + if err != nil { + t.Fatalf("generate organization ID: %v", err) + } + created, err := createNeed(input, organizationID, needID, now) + if err != nil { + t.Fatalf("createNeed() error = %v", err) + } + return created +} + +func testNeedTime() time.Time { + return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) +} + +func hasRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool { + canonical := canonicalNeedKey(value) + for _, suggestion := range suggestions { + if suggestion.Field == field && suggestion.Value == canonical { + return true + } + } + return false +} diff --git a/backend/internal/usecase/need/parse_rules.go b/backend/internal/usecase/need/parse_rules.go new file mode 100644 index 0000000..babbb86 --- /dev/null +++ b/backend/internal/usecase/need/parse_rules.go @@ -0,0 +1,317 @@ +package need + +import ( + "fmt" + "regexp" + "sort" + "strings" + "unicode" + "unicode/utf8" + + "lincodex/backend/internal/domain" +) + +const needRulesVersion = "need-rules.2026-10.1" + +var ( + needSectionPattern = regexp.MustCompile(`(?i)(обязательно|обязательные навыки|требуемые навыки|требования|желательно|желательные навыки|предпочтительно|технологии|стек|required skills|requirements|preferred skills|technology stack)\s*:?\s*`) + needTaskPattern = regexp.MustCompile(`(?i)(задачи|обязанности|tasks|responsibilities)\s*:`) + needNegationPattern = regexp.MustCompile(`(?i)(?:без|without|no|not(?:\s+required)?|не(?:\s+(?:требуется|нужен|нужна|нужно|обязательно|обязателен|обязательна|обязательны|требуемый|требуемая))?)\s*[:,\-]?\s*$`) + needDomainPatterns = []domainRule{ + {pattern: regexp.MustCompile(`(?i)(в команду платежей)`), value: "платежи"}, + {pattern: regexp.MustCompile(`(?i)(в команду выплат)`), value: "выплаты"}, + {pattern: regexp.MustCompile(`(?i)(payments team)`), value: "payments"}, + {pattern: regexp.MustCompile(`(?i)(logistics team)`), value: "logistics"}, + } + needSpecializationPatterns = []domainRule{ + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:backend[ -](?:developer|engineer)|back-end[ -](?:developer|engineer)|бэкенд[- ]разработчик\p{L}*|бэкэнд[- ]разработчик\p{L}*|серверн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationBackend)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:frontend[ -](?:developer|engineer)|front-end[ -](?:developer|engineer)|фронтенд[- ]разработчик\p{L}*|фронтэнд[- ]разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationFrontend)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:mobile[ -](?:developer|engineer)|мобильн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationMobile)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(network engineer|сетев\p{L}* инженер\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationNetworkEngineer)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(devops|sre)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDevopsSRE)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data analyst|аналитик данных)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDataAnalyst)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data scientist|machine learning|ml engineer|специалист\p{L}* машинн\p{L}* обучен\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDSML)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(information security|информационн\p{L}* безопасност\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationInformationSecurity)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(qa engineer|тестировщик\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationQA)}, + } + needGradePatterns = []domainRule{ + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(intern|internship|стаж[её]р\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeIntern)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(junior|jun|джуниор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeJunior)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(middle|mid|мидл\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeMiddle)}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(senior|sen|сеньор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeSenior)}, + {pattern: regexp.MustCompile(`(?i)(младш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeJunior)}, + {pattern: regexp.MustCompile(`(?i)(средн(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeMiddle)}, + {pattern: regexp.MustCompile(`(?i)(старш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeSenior)}, + {pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(младш(?:ий|его|ему))`), value: string(domain.GradeJunior)}, + {pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(средн(?:ий|его|ему))`), value: string(domain.GradeMiddle)}, + {pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(старш(?:ий|его|ему))`), value: string(domain.GradeSenior)}, + } + needWorkFormatRules = []formatRule{ + {pattern: regexp.MustCompile(`(?i)(удал[её]нн\p{L}*|дистанционн\p{L}*|remote)`), value: domain.NeedWorkFormatRemote}, + {pattern: regexp.MustCompile(`(?i)(офис\p{L}*|office)`), value: domain.NeedWorkFormatOffice}, + {pattern: regexp.MustCompile(`(?i)(гибрид\p{L}*|hybrid)`), value: domain.NeedWorkFormatHybrid}, + } + needSkillRules = []skillRule{ + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(postgresql)(?:$|[^\p{L}\p{N}_])`), name: "PostgreSQL", taxonomy: "postgresql"}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(kafka)(?:$|[^\p{L}\p{N}_])`), name: "Kafka", taxonomy: "kafka"}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(temporal)(?:$|[^\p{L}\p{N}_])`), name: "Temporal"}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(docker)(?:$|[^\p{L}\p{N}_])`), name: "Docker", taxonomy: "docker"}, + {pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(go)(?:$|[^\p{L}\p{N}_])`), name: "Go", taxonomy: "go"}, + } +) + +type domainRule struct { + pattern *regexp.Regexp + value string +} + +type formatRule struct { + pattern *regexp.Regexp + value domain.NeedWorkFormat +} + +type skillRule struct { + pattern *regexp.Regexp + name string + taxonomy string +} + +type needTextSection struct { + start int + end int + quote string + want bool +} + +type skillOccurrence struct { + start int + name string + taxonomy string + quote string + section needTextSection +} + +const maxParsedEvidenceRunes = 300 + +func parseSourceText(source string, version int64) domain.NeedRequirements { + requirements := domain.EmptyNeedRequirements() + requirements.Specialization = parseNeedScalar(source, version, needSpecializationPatterns, func(value string) domain.SpecializationCode { + return domain.SpecializationCode(value) + }) + requirements.Grade = parseNeedScalar(source, version, needGradePatterns, func(value string) domain.GradeCode { + return domain.GradeCode(value) + }) + requirements.Domain = parseNeedScalar(source, version, needDomainPatterns, func(value string) string { + return value + }) + requirements.WorkFormats = parseWorkFormats(source, version) + requirements.RequiredSkills, requirements.DesiredSkills = parseSkills(source, version) + requirements.Tasks = parseTasks(source, version) + return requirements +} + +func parseNeedScalar[T any](source string, version int64, rules []domainRule, convert func(string) T) domain.NeedValue[T] { + type candidate struct { + start int + value T + quote string + } + found := make([]candidate, 0, len(rules)) + values := make(map[string]struct{}, len(rules)) + for _, rule := range rules { + for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) { + if len(indices) < 4 || hasNeedNegation(source, indices[2]) { + continue + } + value := convert(rule.value) + key := fmt.Sprint(value) + values[key] = struct{}{} + found = append(found, candidate{ + start: indices[2], value: value, + quote: strings.TrimSpace(source[indices[2]:indices[3]]), + }) + } + } + if len(values) != 1 || len(found) == 0 { + return unknownNeedValue[T]() + } + sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start }) + value := found[0].value + return domain.NeedValue[T]{Status: domain.NeedValueExtracted, Value: &value, Source: extractedNeedSource(found[0].quote, version)} +} + +func parseWorkFormats(source string, version int64) domain.NeedValue[[]domain.NeedWorkFormat] { + type foundFormat struct { + start int + end int + format domain.NeedWorkFormat + } + found := make([]foundFormat, 0, len(needWorkFormatRules)) + seen := make(map[domain.NeedWorkFormat]struct{}, len(needWorkFormatRules)) + for _, rule := range needWorkFormatRules { + for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) { + if len(indices) < 4 || hasNeedNegation(source, indices[2]) { + continue + } + if _, ok := seen[rule.value]; ok { + continue + } + seen[rule.value] = struct{}{} + found = append(found, foundFormat{start: indices[2], end: indices[3], format: rule.value}) + } + } + if len(found) == 0 { + return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown} + } + sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start }) + formats := make([]domain.NeedWorkFormat, 0, len(found)) + for _, item := range found { + formats = append(formats, item.format) + } + quote := strings.TrimSpace(source[found[0].start:found[len(found)-1].end]) + if utf8.RuneCountInString(quote) > maxParsedEvidenceRunes { + return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown} + } + value := formats + return domain.NeedValue[[]domain.NeedWorkFormat]{ + Status: domain.NeedValueExtracted, + Value: &value, + Source: extractedNeedSource(quote, version), + } +} + +func parseSkills(source string, version int64) ([]domain.NeedSkill, []domain.NeedSkill) { + sections := skillSections(source) + occurrences := make([]skillOccurrence, 0, len(needSkillRules)) + for _, section := range sections { + segment := source[section.start:section.end] + for _, rule := range needSkillRules { + for _, indices := range rule.pattern.FindAllStringSubmatchIndex(segment, -1) { + if len(indices) < 4 || hasNeedNegation(source, section.start+indices[2]) { + continue + } + start := section.start + indices[2] + occurrences = append(occurrences, skillOccurrence{ + start: start, name: rule.name, taxonomy: rule.taxonomy, + quote: source[section.start+indices[2] : section.start+indices[3]], section: section, + }) + } + } + } + sort.Slice(occurrences, func(i, j int) bool { return occurrences[i].start < occurrences[j].start }) + seen := make(map[string]struct{}, len(occurrences)) + required := make([]domain.NeedSkill, 0, len(occurrences)) + desired := make([]domain.NeedSkill, 0, len(occurrences)) + for _, occurrence := range occurrences { + key := strings.ToLower(occurrence.name) + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + var taxonomy *string + if occurrence.taxonomy != "" { + value := occurrence.taxonomy + taxonomy = &value + } + item := domain.NeedSkill{ + Name: occurrence.name, TaxonomyCode: taxonomy, Status: domain.NeedItemExtracted, + Source: *extractedNeedSource(skillQuote(occurrence), version), + } + if occurrence.section.want { + desired = append(desired, item) + } else { + required = append(required, item) + } + } + return required, desired +} + +func skillQuote(occurrence skillOccurrence) string { + if occurrence.section.quote != "" && utf8.RuneCountInString(occurrence.section.quote) <= maxParsedEvidenceRunes { + return occurrence.section.quote + } + return occurrence.quote +} + +func skillSections(source string) []needTextSection { + matches := needSectionPattern.FindAllStringSubmatchIndex(source, -1) + if len(matches) == 0 { + return []needTextSection{{start: 0, end: len(source), quote: ""}} + } + sections := make([]needTextSection, 0, len(matches)) + for index, match := range matches { + end := len(source) + if index+1 < len(matches) { + end = matches[index+1][0] + } + if sentenceEnd := strings.IndexAny(source[match[1]:end], ".!?\n"); sentenceEnd >= 0 { + end = match[1] + sentenceEnd + } + segment := strings.TrimSpace(source[match[0]:end]) + if segment == "" { + continue + } + want := isDesiredSection(source[match[2]:match[3]]) + sections = append(sections, needTextSection{start: match[0], end: end, quote: segment, want: want}) + } + if len(sections) == 0 { + return []needTextSection{{start: 0, end: len(source), quote: ""}} + } + return sections +} + +func isDesiredSection(label string) bool { + label = strings.ToLower(label) + return strings.Contains(label, "желат") || strings.Contains(label, "предпочт") || strings.Contains(label, "preferred") +} + +func hasNeedNegation(source string, start int) bool { + if start < 0 || start > len(source) { + return false + } + prefix := source[:start] + if boundary := strings.LastIndexAny(prefix, ".!?;,\n"); boundary >= 0 { + prefix = prefix[boundary+1:] + } + return needNegationPattern.MatchString(prefix) +} + +func parseTasks(source string, version int64) []domain.NeedTask { + indices := needTaskPattern.FindStringSubmatchIndex(source) + if len(indices) < 4 { + return []domain.NeedTask{} + } + start := indices[1] + end := len(source) + if sentenceEnd := strings.IndexAny(source[start:], ".!?\n"); sentenceEnd >= 0 { + end = start + sentenceEnd + } + text := strings.TrimSpace(source[start:end]) + text = strings.Trim(text, " :;,-\t\r") + quote := strings.TrimSpace(source[indices[0]:end]) + if text == "" || utf8.RuneCountInString(text) > maxParsedEvidenceRunes || utf8.RuneCountInString(quote) > maxParsedEvidenceRunes { + return []domain.NeedTask{} + } + value := []rune(text) + value[0] = unicode.ToUpper(value[0]) + text = string(value) + return []domain.NeedTask{{ + Text: text, Status: domain.NeedItemExtracted, + Source: *extractedNeedSource(quote, version), + }} +} + +func extractedNeedSource(quote string, version int64) *domain.NeedValueSource { + versionLabel := needRulesVersion + var quoteValue *string + if quote != "" { + quoteValue = "e + } + extractedVersion := version + return &domain.NeedValueSource{ + Origin: domain.NeedValueExtractedFromText, + Quote: quoteValue, + ExtractedInVersion: &extractedVersion, + ExtractionVersion: &versionLabel, + } +} diff --git a/backend/internal/usecase/need/parse_rules_test.go b/backend/internal/usecase/need/parse_rules_test.go new file mode 100644 index 0000000..d77a0e1 --- /dev/null +++ b/backend/internal/usecase/need/parse_rules_test.go @@ -0,0 +1,129 @@ +package need + +import ( + "testing" + + "lincodex/backend/internal/domain" +) + +func TestParseSourceTextUsesDeterministicSuggestions(t *testing.T) { + const source = "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно." + requirements := parseSourceText(source, 1) + + if got := requirements.Specialization; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != domain.SpecializationBackend { + t.Fatalf("specialization = %+v, want an extracted backend suggestion", got) + } + if got := requirements.Specialization.Source; got == nil || got.Quote == nil || *got.Quote != "Ищем бэкенд-разработчика" || *got.ExtractedInVersion != 1 || *got.ExtractionVersion != needRulesVersion { + t.Fatalf("specialization provenance = %+v, want exact source and rules version", got) + } + if got := requirements.Grade; got.Status != domain.NeedValueUnknown || got.Value != nil || got.Source != nil { + t.Fatalf("grade = %+v, want unknown", got) + } + if got := requirements.Domain; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != "платежи" || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "в команду платежей" { + t.Fatalf("domain = %+v, want a quoted suggestion", got) + } + if got := requirements.WorkFormats; got.Status != domain.NeedValueExtracted || got.Value == nil || len(*got.Value) != 1 || (*got.Value)[0] != domain.NeedWorkFormatRemote || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "удаленно" { + t.Fatalf("work formats = %+v, want a quoted remote suggestion", got) + } + if len(requirements.RequiredSkills) != 3 || len(requirements.DesiredSkills) != 1 { + t.Fatalf("skill counts = %d required, %d desired, want 3 and 1", len(requirements.RequiredSkills), len(requirements.DesiredSkills)) + } + wantRequired := []struct { + name string + taxonomy *string + }{ + {name: "Go", taxonomy: needStringPointer("go")}, + {name: "PostgreSQL", taxonomy: needStringPointer("postgresql")}, + {name: "Temporal"}, + } + for index, want := range wantRequired { + got := requirements.RequiredSkills[index] + if got.Name != want.name || got.Status != domain.NeedItemExtracted || !equalNeedStringPointer(got.TaxonomyCode, want.taxonomy) { + t.Errorf("required_skills[%d] = %+v, want name %q, extracted, taxonomy %v", index, got, want.name, want.taxonomy) + } + if got.Source.Origin != domain.NeedValueExtractedFromText || got.Source.Quote == nil || *got.Source.Quote != "Обязательно: Go, PostgreSQL и Temporal" || got.Source.ExtractedInVersion == nil || *got.Source.ExtractedInVersion != 1 { + t.Errorf("required_skills[%d] provenance = %+v, want the exact required section", index, got.Source) + } + } + desired := requirements.DesiredSkills[0] + if desired.Name != "Kafka" || desired.Status != domain.NeedItemExtracted || desired.Source.Quote == nil || *desired.Source.Quote != "Желательно опыт с Kafka" { + t.Fatalf("desired skill = %+v, want a quoted extracted Kafka suggestion", desired) + } + if len(requirements.Tasks) != 1 || requirements.Tasks[0].Text != "Развивать сервис выплат и переводить его на событийную модель" || requirements.Tasks[0].Status != domain.NeedItemExtracted { + t.Fatalf("tasks = %+v, want one extracted task", requirements.Tasks) + } + if got := requirements.Tasks[0].Source.Quote; got == nil || *got != "Задачи: развивать сервис выплат и переводить его на событийную модель" { + t.Fatalf("task quote = %v, want exact source excerpt", got) + } + if requirements.Location.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown { + t.Fatalf("location or salary was inferred: location=%+v salary=%+v", requirements.Location, requirements.Salary) + } +} + +func TestParseSourceTextDoesNotSupplyDefaultsOrDuplicateSkills(t *testing.T) { + requirements := parseSourceText("Разработчик использует GO и go, зарплата обсуждается позже.", 2) + if requirements.Grade.Status != domain.NeedValueUnknown || requirements.WorkFormats.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown { + t.Fatalf("parser supplied an absent value: grade=%+v formats=%+v salary=%+v", requirements.Grade, requirements.WorkFormats, requirements.Salary) + } + if len(requirements.RequiredSkills) != 1 || requirements.RequiredSkills[0].Name != "Go" { + t.Fatalf("required skills = %+v, want one case-insensitive suggestion", requirements.RequiredSkills) + } + if got := requirements.RequiredSkills[0].Source; got.ExtractedInVersion == nil || *got.ExtractedInVersion != 2 { + t.Fatalf("source version = %+v, want version 2", got) + } +} + +func TestParseSourceTextCanSuggestExplicitGrade(t *testing.T) { + requirements := parseSourceText("Нужен backend developer уровня Junior. Обязательно: Go.", 1) + if requirements.Grade.Status != domain.NeedValueExtracted || requirements.Grade.Value == nil || *requirements.Grade.Value != domain.GradeJunior { + t.Fatalf("grade = %+v, want extracted junior suggestion", requirements.Grade) + } + if requirements.Grade.Source == nil || requirements.Grade.Source.Quote == nil || *requirements.Grade.Source.Quote != "Junior" { + t.Fatalf("grade provenance = %+v, want exact source term", requirements.Grade.Source) + } +} + +func TestParseSourceTextLeavesAmbiguousOrIncidentalGradesUnknown(t *testing.T) { + for _, source := range []string{ + "Нужен backend developer уровня Junior или Senior.", + "Возраст: старше 35 лет, младше 30 лет, среднее образование.", + } { + requirements := parseSourceText(source, 1) + if requirements.Grade.Status != domain.NeedValueUnknown { + t.Errorf("grade for %q = %+v, want unknown", source, requirements.Grade) + } + } +} + +func TestParseSourceTextLeavesAmbiguousSpecializationUnknown(t *testing.T) { + requirements := parseSourceText("Нужен backend developer и frontend engineer.", 1) + if requirements.Specialization.Status != domain.NeedValueUnknown { + t.Fatalf("specialization = %+v, want unknown for conflicting roles", requirements.Specialization) + } +} + +func TestParseSourceTextSkipsNegatedRequirements(t *testing.T) { + requirements := parseSourceText("Не Senior и не требуется PostgreSQL; без Go.", 1) + if requirements.Grade.Status != domain.NeedValueUnknown { + t.Fatalf("grade = %+v, want unknown for a negated value", requirements.Grade) + } + if len(requirements.RequiredSkills) != 0 || len(requirements.DesiredSkills) != 0 { + t.Fatalf("skills = required %v, desired %v; want no negated suggestions", requirements.RequiredSkills, requirements.DesiredSkills) + } +} + +func TestParseSourceTextUsesUnicodeAwareEnglishBoundaries(t *testing.T) { + requirements := parseSourceText("ищем xjunior разработчика, разрабатываем goплатформу", 1) + if requirements.Grade.Status != domain.NeedValueUnknown || len(requirements.RequiredSkills) != 0 { + t.Fatalf("grade=%+v skills=%v; want no substring matches", requirements.Grade, requirements.RequiredSkills) + } +} + +func needStringPointer(value string) *string { return &value } + +func equalNeedStringPointer(left, right *string) bool { + if left == nil || right == nil { + return left == right + } + return *left == *right +} diff --git a/backend/internal/usecase/need/service.go b/backend/internal/usecase/need/service.go new file mode 100644 index 0000000..4a42fac --- /dev/null +++ b/backend/internal/usecase/need/service.go @@ -0,0 +1,370 @@ +package need + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + createOperation = "organization_need.create" + createLocation = "need.Service.Create" + maxIdempotencyKeySize = 255 + maxCanonicalBodySize = 1 << 20 + purgeExpiredBatch = 100 +) + +// Keyring computes scoped idempotency digests. identity.Keyring implements +// this interface so need commands use the existing server secret and store. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// Dependencies configure one stateless need service. +type Dependencies struct { + Transactor outbound.Transactor + Keyring Keyring + Clock func() time.Time +} + +// Service applies organization-scoped need commands and reads. +type Service struct { + transactor outbound.Transactor + keyring Keyring + clock func() time.Time +} + +// NewService fails at startup when a required dependency is missing. +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil { + return nil, errors.New("need.NewService - every dependency must be set") + } + return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil +} + +// CreateCommand binds the authenticated actor and path organization to one +// validated create request. +type CreateCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + IdempotencyKey string + CanonicalBody []byte + Input CreateInput +} + +// Create returns the original immutable response snapshot, including on an +// identical retry after the live need has changed. +func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.NeedResponseSnapshot, error) { + request, err := service.prepareCreate(command) + if err != nil { + return domain.NeedResponseSnapshot{}, err + } + var result domain.NeedResponseSnapshot + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = service.createInTransaction(ctx, unit, command, request) + return err + }) + if err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - run transaction: %w", createLocation, err) + } + return result, nil +} + +func (service *Service) createInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateCommand, + request createRequest, +) (domain.NeedResponseSnapshot, error) { + if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil { + return domain.NeedResponseSnapshot{}, err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err) + } + if !created { + return replayNeedCreation(ctx, unit.NeedCreationResults(), request, command.OrganizationID, stored) + } + needID, err := uuid.NewV7() + if err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - generate need ID: %w", createLocation, err) + } + createdNeed, err := createNeed(command.Input, command.OrganizationID, needID, request.now) + if err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate need: %w", createLocation, err) + } + snapshot := createdNeed.ResponseSnapshot() + if err := validateCreationResultSize(snapshot); err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, err) + } + if err := unit.Needs().Create(ctx, createdNeed); err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err) + } + if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) + } + return snapshot, nil +} + +func replayNeedCreation( + ctx context.Context, + results outbound.NeedCreationResultRepository, + request createRequest, + organizationID uuid.UUID, + stored outbound.IdempotencyRecord, +) (domain.NeedResponseSnapshot, error) { + if stored.Fingerprint != request.fingerprint { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused) + } + snapshot, err := results.GetCreationResult(ctx, request.scope) + if err != nil { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read immutable creation response: %w", createLocation, err) + } + result, err := domain.RestoreNeedResponseSnapshot(snapshot) + if err != nil || result.Need.OrganizationID != organizationID { + return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, domain.ErrInvalidNeed) + } + return result, nil +} + +func validateCreationResultSize(snapshot domain.NeedResponseSnapshot) error { + encoded, err := json.Marshal(snapshot) + if err != nil { + return fmt.Errorf("%s - encode immutable creation response: %w", createLocation, err) + } + if len(encoded) > domain.MaxNeedCreationResultBytes { + return invalidRequest("", "combined need response exceeds its storage bound") + } + return nil +} + +type createRequest struct { + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) { + const location = "need.Service.prepareCreate" + switch { + case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil: + return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) + case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize: + return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidCreateRequest) + } + fingerprint := service.keyring.Fingerprint(command.CanonicalBody) + principal := command.ActorID.String() + ":" + command.OrganizationID.String() + scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal) + now := service.clock().UTC().Truncate(time.Microsecond) + if !validNeedApplicationTime(now) { + return createRequest{}, invalidRequest("", "application time must be representable by the need contract") + } + expiresAt := now.Add(outbound.IdempotencyRetention) + if !validNeedApplicationTime(expiresAt) { + return createRequest{}, invalidRequest("", "idempotency expiry exceeds the need contract date range") + } + record := outbound.IdempotencyRecord{ + Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt, + } + return createRequest{fingerprint: fingerprint, scope: scope, record: record, now: now}, nil +} + +// ListCommand selects an owner-scoped page of needs. +type ListCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + After *outbound.NeedListPosition + Limit int32 +} + +// List reads one page after checking the current account and owner membership +// in the same transaction. +func (service *Service) List(ctx context.Context, command ListCommand) (outbound.NeedPage, error) { + const location = "need.Service.List" + if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil { + return outbound.NeedPage{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + } + if command.Limit < 1 || command.Limit > outbound.MaxNeedPageSize { + return outbound.NeedPage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed) + } + var result outbound.NeedPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil { + return err + } + page, err := unit.NeedLists().List(ctx, outbound.NeedListQuery{ + OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit, + }) + if err != nil { + return fmt.Errorf("%s - list organization needs: %w", location, err) + } + result = page + return nil + }) + if err != nil { + return outbound.NeedPage{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// Get reads the current need version for an active owner. +func (service *Service) Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error) { + const location = "need.Service.Get" + if actorID == uuid.Nil || organizationID == uuid.Nil || needID == uuid.Nil { + return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden) + } + var result domain.Need + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeNeedOwner(ctx, unit, actorID, organizationID, location); err != nil { + return err + } + need, err := unit.Needs().Get(ctx, organizationID, needID) + if err != nil { + return fmt.Errorf("%s - read organization need: %w", location, err) + } + result = need + return nil + }) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// Update replaces the fields explicitly supplied by an active owner and +// commits one immutable version when the merged request changes content. +func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Need, error) { + const location = "need.Service.Update" + if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil || command.NeedID == uuid.Nil { + return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden) + } + if command.Input.ExpectedVersion < 1 { + return domain.Need{}, invalidRequest("/expected_version", "must be positive") + } + now := service.clock().UTC().Truncate(time.Microsecond) + if !validNeedApplicationTime(now) { + return domain.Need{}, invalidRequest("", "application time must be representable by the need contract") + } + var result domain.Need + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = service.updateInTransaction(ctx, unit, command, now) + return err + }) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func validNeedApplicationTime(value time.Time) bool { + return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 +} + +func (service *Service) updateInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command UpdateCommand, + now time.Time, +) (domain.Need, error) { + const location = "need.Service.Update" + if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil { + return domain.Need{}, err + } + store := unit.Needs() + current, err := store.Get(ctx, command.OrganizationID, command.NeedID) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - read organization need: %w", location, err) + } + updated, changed, err := reviseNeed(current, command.Input, now) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - merge need update: %w", location, err) + } + if !changed { + return updated, nil + } + if err := store.Save(ctx, command.OrganizationID, command.NeedID, current.Version(), updated); err != nil { + if !errors.Is(err, outbound.ErrNeedVersionConflict) { + return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, err) + } + return service.recoverConcurrentUpdate(ctx, store, command, now) + } + return updated, nil +} + +func (service *Service) recoverConcurrentUpdate( + ctx context.Context, + store outbound.NeedRepository, + command UpdateCommand, + now time.Time, +) (domain.Need, error) { + const location = "need.Service.Update" + latest, err := store.Get(ctx, command.OrganizationID, command.NeedID) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - read winning need version: %w", location, err) + } + latest, changed, err := reviseNeed(latest, command.Input, now) + if err != nil { + return domain.Need{}, fmt.Errorf("%s - compare concurrent need update: %w", location, err) + } + if changed { + return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, outbound.ErrNeedVersionConflict) + } + return latest, nil +} + +// UpdateCommand binds one versioned replacement to a trusted actor and path. +type UpdateCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + NeedID uuid.UUID + Input UpdateInput +} + +func authorizeNeedOwner( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + location string, +) error { + user, err := unit.Users().GetByID(ctx, actorID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden) + } + return fmt.Errorf("%s - read account: %w", location, err) + } + if user.Scenario != domain.ScenarioEmployer { + return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden) + } + if !user.EmailVerified() { + return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified) + } + membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID) + if err != nil { + if errors.Is(err, outbound.ErrOrganizationNotFound) { + return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound) + } + return fmt.Errorf("%s - lock active membership: %w", location, err) + } + if membership.Role() != domain.OrganizationRoleOwner { + return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired) + } + return nil +} diff --git a/backend/internal/usecase/need/service_test.go b/backend/internal/usecase/need/service_test.go new file mode 100644 index 0000000..035f76a --- /dev/null +++ b/backend/internal/usecase/need/service_test.go @@ -0,0 +1,477 @@ +package need + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type serviceTestKeyring struct{} + +func (serviceTestKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte { + return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal)) +} + +func (serviceTestKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte { + return sha256.Sum256(body) +} + +type serviceTestState struct { + users map[uuid.UUID]domain.User + memberships map[serviceTestMembershipKey]domain.Membership + needs map[serviceTestNeedKey]domain.Need + versions map[serviceTestVersionKey]domain.Need + idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord + results map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot + createCount int + updateCount int +} + +type serviceTestMembershipKey struct { + organizationID uuid.UUID + userID uuid.UUID +} + +type serviceTestNeedKey struct { + organizationID uuid.UUID + needID uuid.UUID +} + +type serviceTestVersionKey struct { + serviceTestNeedKey + + version int64 +} + +func newServiceTestState() serviceTestState { + return serviceTestState{ + users: map[uuid.UUID]domain.User{}, memberships: map[serviceTestMembershipKey]domain.Membership{}, + needs: map[serviceTestNeedKey]domain.Need{}, versions: map[serviceTestVersionKey]domain.Need{}, + idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{}, + results: map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot{}, + } +} + +func (state serviceTestState) clone() serviceTestState { + cloned := newServiceTestState() + for id, user := range state.users { + cloned.users[id] = user + } + for key, membership := range state.memberships { + cloned.memberships[key] = membership + } + for key, need := range state.needs { + copyNeed, err := domain.RestoreNeed(need.Snapshot()) + if err != nil { + panic(err) + } + cloned.needs[key] = copyNeed + } + for key, need := range state.versions { + copyNeed, err := domain.RestoreNeed(need.Snapshot()) + if err != nil { + panic(err) + } + cloned.versions[key] = copyNeed + } + for scope, record := range state.idempotency { + cloned.idempotency[scope] = record + } + for scope, result := range state.results { + copyResult, err := domain.RestoreNeedResponseSnapshot(result) + if err != nil { + panic(err) + } + cloned.results[scope] = copyResult + } + cloned.createCount = state.createCount + cloned.updateCount = state.updateCount + return cloned +} + +type serviceTestTransactor struct { + mu sync.Mutex + + state serviceTestState + failResultSave bool +} + +func newServiceTestTransactor(state serviceTestState) *serviceTestTransactor { + return &serviceTestTransactor{state: state} +} + +func (transactor *serviceTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { + transactor.mu.Lock() + defer transactor.mu.Unlock() + working := transactor.state.clone() + unit := &serviceTestUnit{state: &working, failResultSave: transactor.failResultSave} + if err := work(ctx, unit); err != nil { + return err + } + transactor.state = working + return nil +} + +func (transactor *serviceTestTransactor) snapshot() serviceTestState { + transactor.mu.Lock() + defer transactor.mu.Unlock() + return transactor.state.clone() +} + +type serviceTestUnit struct { + outbound.UnitOfWork + + state *serviceTestState + failResultSave bool +} + +func (unit *serviceTestUnit) Users() outbound.UserRepository { + return serviceTestUsers{state: unit.state} +} + +func (unit *serviceTestUnit) Organizations() outbound.OrganizationRepository { + return serviceTestOrganizations{state: unit.state} +} + +func (unit *serviceTestUnit) IdempotencyRecords() outbound.IdempotencyRepository { + return serviceTestIdempotency{state: unit.state} +} + +func (unit *serviceTestUnit) Needs() outbound.NeedRepository { + return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave} +} + +func (unit *serviceTestUnit) NeedLists() outbound.NeedListRepository { + return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave} +} + +func (unit *serviceTestUnit) NeedCreationResults() outbound.NeedCreationResultRepository { + return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave} +} + +type serviceTestUsers struct { + outbound.UserRepository + + state *serviceTestState +} + +func (repository serviceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.state.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +type serviceTestOrganizations struct { + outbound.OrganizationRepository + + state *serviceTestState +} + +func (repository serviceTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) { + membership, ok := repository.state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}] + if !ok || !membership.GrantsAccess() { + return domain.Membership{}, outbound.ErrOrganizationNotFound + } + return membership, nil +} + +type serviceTestIdempotency struct { + outbound.IdempotencyRepository + + state *serviceTestState +} + +func (repository serviceTestIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) { + if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) { + return existing, false, nil + } + repository.state.idempotency[record.Scope] = record + return record, true, nil +} + +func (repository serviceTestIdempotency) Find(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, at time.Time) (outbound.IdempotencyRecord, error) { + record, ok := repository.state.idempotency[scope] + if !ok || !record.ExpiresAt.After(at) { + return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound + } + return record, nil +} + +func (repository serviceTestIdempotency) PurgeExpired(_ context.Context, at time.Time, limit int32) (int64, error) { + var deleted int64 + for scope, record := range repository.state.idempotency { + if deleted >= int64(limit) { + break + } + if !record.ExpiresAt.After(at) { + delete(repository.state.idempotency, scope) + delete(repository.state.results, scope) + deleted++ + } + } + return deleted, nil +} + +type serviceTestNeeds struct { + outbound.NeedRepository + + state *serviceTestState + failResultSave bool +} + +func (repository serviceTestNeeds) Create(_ context.Context, need domain.Need) error { + key := serviceTestNeedKey{organizationID: need.OrganizationID(), needID: need.ID()} + if _, exists := repository.state.needs[key]; exists { + return outbound.ErrNeedAlreadyExists + } + repository.state.needs[key] = need + repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: need.Version()}] = need + repository.state.createCount++ + return nil +} + +func (repository serviceTestNeeds) Get(_ context.Context, organizationID, needID uuid.UUID) (domain.Need, error) { + need, ok := repository.state.needs[serviceTestNeedKey{organizationID: organizationID, needID: needID}] + if !ok { + return domain.Need{}, outbound.ErrNeedNotFound + } + return need, nil +} + +func (repository serviceTestNeeds) GetVersion(_ context.Context, organizationID, needID uuid.UUID, version int64) (domain.Need, error) { + need, ok := repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: serviceTestNeedKey{organizationID: organizationID, needID: needID}, version: version}] + if !ok { + return domain.Need{}, outbound.ErrNeedNotFound + } + return need, nil +} + +func (repository serviceTestNeeds) Save(_ context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error { + key := serviceTestNeedKey{organizationID: organizationID, needID: needID} + current, ok := repository.state.needs[key] + if !ok { + return outbound.ErrNeedNotFound + } + if !current.IsNextVersionOf(next, expectedVersion) { + return outbound.ErrNeedVersionConflict + } + repository.state.needs[key] = next + repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: next.Version()}] = next + repository.state.updateCount++ + return nil +} + +func (repository serviceTestNeeds) List(_ context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) { + items := make([]domain.Need, 0) + for key, need := range repository.state.needs { + if key.organizationID != query.OrganizationID { + continue + } + position := outbound.NeedCreationPosition(need) + if query.After != nil && needPositionIsNotBefore(position, *query.After) { + continue + } + items = append(items, need) + } + for left := 0; left < len(items); left++ { + for right := left + 1; right < len(items); right++ { + leftPosition, rightPosition := outbound.NeedCreationPosition(items[left]), outbound.NeedCreationPosition(items[right]) + if rightPosition.CreatedAt.After(leftPosition.CreatedAt) || rightPosition.CreatedAt.Equal(leftPosition.CreatedAt) && rightPosition.NeedID.String() > leftPosition.NeedID.String() { + items[left], items[right] = items[right], items[left] + } + } + } + page := outbound.NeedPage{Items: make([]domain.Need, 0, min(int(query.Limit), len(items)))} + if len(items) > int(query.Limit) { + page.HasMore = true + items = items[:query.Limit] + } + page.Items = append(page.Items, items...) + return page, nil +} + +func needPositionIsNotBefore(position, after outbound.NeedListPosition) bool { + if position.CreatedAt.After(after.CreatedAt) { + return true + } + if position.CreatedAt.Before(after.CreatedAt) { + return false + } + return position.NeedID.String() >= after.NeedID.String() +} + +func (repository serviceTestNeeds) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error { + if repository.failResultSave { + return errors.New("simulated response snapshot failure") + } + if _, ok := repository.state.idempotency[scope]; !ok { + return outbound.ErrIdempotencyRecordNotFound + } + repository.state.results[scope] = snapshot + return nil +} + +func (repository serviceTestNeeds) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error) { + snapshot, ok := repository.state.results[scope] + if !ok { + return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound + } + return snapshot, nil +} + +func newNeedServiceHarness(t *testing.T) (*Service, *serviceTestTransactor, uuid.UUID, uuid.UUID, func(time.Time)) { + t.Helper() + now := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC) + current := now + userID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + verifiedAt := now.Add(-time.Hour) + state := newServiceTestState() + state.users[userID] = domain.User{ID: userID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt} + membership, err := domain.NewOwnerMembership(organizationID, userID, now) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}] = membership + transactor := newServiceTestTransactor(state) + service, err := NewService(Dependencies{Transactor: transactor, Keyring: serviceTestKeyring{}, Clock: func() time.Time { return current }}) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + setTime := func(value time.Time) { current = value } + return service, transactor, userID, organizationID, setTime +} + +func testNeedCreateCommand(actorID, organizationID uuid.UUID, key, title string) CreateCommand { + return CreateCommand{ + ActorID: actorID, OrganizationID: organizationID, IdempotencyKey: key, + CanonicalBody: []byte(fmt.Sprintf(`{"title":%q}`, title)), + Input: CreateInput{Title: title}, + } +} + +func TestCreateReplaysOriginalNeedAfterUpdate(t *testing.T) { + service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t) + command := testNeedCreateCommand(actorID, organizationID, "request-1", "Initial need") + created, err := service.Create(t.Context(), command) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + updated, err := service.Update(t.Context(), UpdateCommand{ + ActorID: actorID, OrganizationID: organizationID, NeedID: created.Need.ID, + Input: UpdateInput{ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated need"}}, + }) + if err != nil || updated.Version() != 2 { + t.Fatalf("Update() version = %d, error = %v", updated.Version(), err) + } + replayed, err := service.Create(t.Context(), command) + if err != nil || replayed.Need.ID != created.Need.ID || replayed.Need.Version != 1 || replayed.Need.Title != "Initial need" { + t.Fatalf("Create(retry) = id %s version %d title %q error %v, want the original response", replayed.Need.ID, replayed.Need.Version, replayed.Need.Title, err) + } + current, err := service.Get(t.Context(), actorID, organizationID, created.Need.ID) + if err != nil || current.Version() != 2 || current.Snapshot().Title != "Updated need" { + t.Fatalf("Get after replay = version %d title %q error %v", current.Version(), current.Snapshot().Title, err) + } + state := transactor.snapshot() + if state.createCount != 1 || state.updateCount != 1 { + t.Fatalf("stored creates = %d updates = %d, want 1 create and 1 update", state.createCount, state.updateCount) + } + command.CanonicalBody = []byte(`{"title":"Different body"}`) + command.Input.Title = "Different body" + if _, err := service.Create(t.Context(), command); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("Create(same key, changed body) error = %v, want ErrIdempotencyKeyReused", err) + } +} + +func TestCreateReusesExpiredIdempotencyScopeAtExactDeadline(t *testing.T) { + service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t) + firstCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "Before expiry") + first, err := service.Create(t.Context(), firstCommand) + if err != nil { + t.Fatalf("Create(first) error = %v", err) + } + setTime(first.Need.CreatedAt.Add(outbound.IdempotencyRetention)) + secondCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "After expiry") + second, err := service.Create(t.Context(), secondCommand) + if err != nil || second.Need.ID == first.Need.ID || second.Need.Title != "After expiry" { + t.Fatalf("Create(expired key) = id %s title %q error %v", second.Need.ID, second.Need.Title, err) + } + state := transactor.snapshot() + if state.createCount != 2 || len(state.results) != 1 { + t.Fatalf("stored creates = %d results = %d, want two creates and one replaced snapshot", state.createCount, len(state.results)) + } + replayed, err := service.Create(t.Context(), secondCommand) + if err != nil || replayed.Need.ID != second.Need.ID || replayed.Need.Title != "After expiry" { + t.Fatalf("Create(replay after reuse) = id %s title %q error %v", replayed.Need.ID, replayed.Need.Title, err) + } +} + +func TestCreateRejectsIdempotencyExpiryOutsideNeedDateRange(t *testing.T) { + service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t) + setTime(time.Date(9999, time.December, 31, 23, 59, 59, 0, time.UTC)) + if _, err := service.Create(t.Context(), testNeedCreateCommand(actorID, organizationID, "request-edge", "Edge need")); !errors.Is(err, ErrInvalidRequest) { + t.Fatalf("Create() at the final contract date error = %v, want ErrInvalidRequest for 24-hour expiry", err) + } + state := transactor.snapshot() + if state.createCount != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { + t.Fatalf("out-of-range expiry wrote state: creates=%d keys=%d results=%d", state.createCount, len(state.idempotency), len(state.results)) + } +} + +func TestCreateRollbackLeavesNoNeedOrReplayResult(t *testing.T) { + service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t) + transactor.failResultSave = true + command := testNeedCreateCommand(actorID, organizationID, "request-3", "Rollback need") + if _, err := service.Create(t.Context(), command); err == nil { + t.Fatal("Create() succeeded despite result snapshot failure") + } + state := transactor.snapshot() + if state.createCount != 0 || len(state.needs) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { + t.Fatalf("failed create left state: creates %d needs %d keys %d results %d", state.createCount, len(state.needs), len(state.idempotency), len(state.results)) + } +} + +func TestConcurrentCreateWithSameKeyCreatesOneNeed(t *testing.T) { + service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t) + command := testNeedCreateCommand(actorID, organizationID, "request-4", "One need") + var group sync.WaitGroup + errorsFound := make(chan error, 2) + ids := make(chan uuid.UUID, 2) + for range 2 { + group.Go(func() { + result, err := service.Create(t.Context(), command) + if err != nil { + errorsFound <- err + return + } + ids <- result.Need.ID + }) + } + group.Wait() + close(errorsFound) + for err := range errorsFound { + t.Fatalf("concurrent Create() error = %v", err) + } + close(ids) + var first uuid.UUID + for id := range ids { + if first != uuid.Nil && first != id { + t.Fatalf("concurrent calls returned different need IDs: %s and %s", first, id) + } + first = id + } + state := transactor.snapshot() + if first == uuid.Nil || state.createCount != 1 || len(state.needs) != 1 { + t.Fatalf("concurrent calls left ID %s, creates %d, needs %d", first, state.createCount, len(state.needs)) + } +} diff --git a/backend/internal/usecase/supportcase/service.go b/backend/internal/usecase/supportcase/service.go new file mode 100644 index 0000000..870ffd5 --- /dev/null +++ b/backend/internal/usecase/supportcase/service.go @@ -0,0 +1,658 @@ +// Package supportcase creates and reads account-owned support cases. +package supportcase + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + ErrForbidden = errors.New("support case operation forbidden") + ErrEmailNotVerified = errors.New("support case operation requires a confirmed email") + ErrIdempotencyKeyReused = errors.New("support case idempotency key was reused") + ErrInvalidIdempotencyKey = errors.New("invalid support case idempotency key") + ErrInvalidCreateRequest = errors.New("invalid support case create request") + ErrStateConflict = errors.New("support case conflicts with current state") + ErrPolicyUnavailable = errors.New("support case policy is unavailable") + ErrRateLimited = errors.New("support case request limit reached") +) + +const ( + createOperation = "support.case.create" + createLocation = "supportcase.Service.Create" + maxIdempotencyKeySize = 255 + maxCanonicalBodySize = 1 << 20 + purgeExpiredBatch = 100 +) + +// Keyring computes scoped idempotency digests. identity.Keyring implements +// this interface so support cases use the existing server secret and storage. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// Dependencies are the collaborators of Service. +type Dependencies struct { + Transactor outbound.Transactor + Keyring Keyring + Clock func() time.Time +} + +// Service applies support-case commands and reads. +type Service struct { + transactor outbound.Transactor + keyring Keyring + clock func() time.Time +} + +func NewService(dependencies Dependencies) (*Service, error) { + if dependencies.Transactor == nil || dependencies.Keyring == nil || dependencies.Clock == nil { + return nil, errors.New("supportcase.NewService - every dependency must be set") + } + return &Service{ + transactor: dependencies.Transactor, + keyring: dependencies.Keyring, + clock: dependencies.Clock, + }, nil +} + +// CreateCommand contains only user-stated fields and the authenticated actor. +// Object data, policy decisions, status, response target, rubric, and staff +// identities are resolved by the service. +type CreateCommand struct { + ActorID uuid.UUID + IdempotencyKey string + CanonicalBody []byte + Type domain.SupportCaseType + Description string + Object *domain.SupportCaseReference + AssessmentTarget *domain.SupportCaseAssessmentTarget + ComplaintReason *domain.SupportCaseComplaintReason +} + +func (CreateCommand) String() string { return "[support case create command]" } +func (CreateCommand) GoString() string { return "[support case create command]" } +func (CreateCommand) LogValue() slog.Value { + return slog.StringValue("[support case create command]") +} + +// CreateResult is the immutable response snapshot for a successful create. +type CreateResult struct { + Case domain.SupportCase + Replayed bool + TargetLate bool +} + +type createRequest struct { + command CreateCommand + scope [outbound.IdempotencyDigestSize]byte + fingerprint [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +type createAttempt struct { + result CreateResult + err error +} + +// Create opens a support case and stores its stable result with the generic +// idempotency record in one transaction. Domain rejections after the request +// budget is consumed are returned only after the transaction commits. +func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) { + request, err := service.prepareCreateRequest(command) + if err != nil { + return CreateResult{}, err + } + var attempt createAttempt + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + attempt, err = service.createInTransaction(ctx, unit, request) + return err + }) + if err != nil { + return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err) + } + return attempt.result, attempt.err +} + +func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) { + const location = "supportcase.Service.prepareCreateRequest" + if command.ActorID == uuid.Nil { + return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) + } + if !validIdempotencyKey(command.IdempotencyKey) { + return createRequest{}, fmt.Errorf("%s - key must have 1 to 255 allowed bytes: %w", location, ErrInvalidIdempotencyKey) + } + canonicalBody := command.CanonicalBody + if len(canonicalBody) == 0 { + var err error + canonicalBody, err = canonicalCreateBody(command) + if err != nil { + return createRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, ErrInvalidCreateRequest) + } + } + if len(canonicalBody) > maxCanonicalBodySize { + return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", location, ErrInvalidCreateRequest) + } + fingerprint := service.keyring.Fingerprint(canonicalBody) + scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String()) + return createRequest{ + command: command, scope: scope, fingerprint: fingerprint, + record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint}, + }, nil +} + +func (service *Service) createInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + request createRequest, +) (createAttempt, error) { + user, err := requireAccount(ctx, unit, request.command.ActorID, createLocation) + if err != nil { + return createAttempt{}, err + } + if user.Scenario == domain.ScenarioEmployer && request.command.Type != domain.SupportCaseTypeSupport { + return createAttempt{}, ErrForbidden + } + repositories, attempts, err := supportCaseRepositories(unit) + if err != nil { + return createAttempt{}, err + } + latestRequestAt, err := repositories.SupportCaseRequestLimits().LockOwner(ctx, request.command.ActorID) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - lock account request budget: %w", createLocation, err) + } + now := service.clock().UTC().Truncate(time.Microsecond) + if now.IsZero() { + return createAttempt{}, fmt.Errorf("%s - application time must be set", createLocation) + } + if latestRequestAt.After(now) { + now = latestRequestAt.UTC().Truncate(time.Microsecond) + } + request.now = now + request.record = outbound.IdempotencyRecord{ + Scope: request.scope, Fingerprint: request.fingerprint, + CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention), + } + version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, request.now) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - read effective product policy: %w", createLocation, err) + } + policy := version.Policy().Support + if policy == nil { + return createAttempt{}, fmt.Errorf("%s - current policy has no support section: %w", createLocation, ErrPolicyUnavailable) + } + limit, err := repositories.SupportCaseRequestLimits().Consume( + ctx, request.command.ActorID, request.now, policy.MaxRequestsPerWindow(), policy.RequestWindow(), + ) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - consume request budget: %w", createLocation, err) + } + if !limit.Allowed { + return createAttempt{err: &RateLimitedError{RetryAfter: limit.RetryAfter}}, nil + } + prepared, attempt, finished, err := prepareCreateInTransaction(ctx, unit, repositories, policy, version.Version(), user, request) + if err != nil || finished { + return attempt, err + } + return createSupportCaseInTransaction(ctx, unit, repositories, attempts, user, prepared) +} + +type preparedSupportCase struct { + request createRequest + fields domain.NewSupportCaseInput +} + +func prepareCreateInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + repositories outbound.SupportCaseRepositories, + policy *domain.SupportPolicy, + policyVersion int32, + user domain.User, + request createRequest, +) (preparedSupportCase, createAttempt, bool, error) { + stored, err := unit.IdempotencyRecords().Find(ctx, request.scope, request.now) + if err == nil { + attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored) + return preparedSupportCase{}, attempt, true, replayErr + } + if !errors.Is(err, outbound.ErrIdempotencyRecordNotFound) { + return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - read idempotency record: %w", createLocation, err) + } + + fields := newCaseInput(request.command, user.ID, domain.SupportResponseTarget{}, request.now) + if validationErr := domain.ValidateSupportCaseRequest(fields); validationErr != nil { + return rejectedCreateRequest(validationErr) + } + responseTarget, err := policy.ResponseTarget(request.command.Type, policyVersion, request.now) + if err != nil { + return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - fix response target: %w", createLocation, err) + } + fields.ResponseTarget = responseTarget + + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err) + } + if !created { + attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored) + return preparedSupportCase{}, attempt, true, replayErr + } + if err := repositories.SupportCaseCreateOutcomes().DeleteCreateOutcome(ctx, request.scope); err != nil { + return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - remove expired create outcome: %w", createLocation, err) + } + return preparedSupportCase{request: request, fields: fields}, createAttempt{}, false, nil +} + +func rejectedCreateRequest(validationErr error) (preparedSupportCase, createAttempt, bool, error) { + return preparedSupportCase{}, createAttempt{err: validationErr}, true, nil +} + +func createSupportCaseInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + repositories outbound.SupportCaseRepositories, + attempts outbound.AssessmentAttemptRepository, + user domain.User, + prepared preparedSupportCase, +) (createAttempt, error) { + request, fields := prepared.request, prepared.fields + if err := resolveReferences(ctx, unit, repositories.SupportCases(), attempts, user, fields); err != nil { + return storeReferenceFailure(ctx, unit, repositories, request, err) + } + if err := resolveManualAssessmentRubric(ctx, repositories, &fields); err != nil { + return createAttempt{}, err + } + + number, err := repositories.SupportCases().NextNumber(ctx, request.now) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - allocate case number: %w", createLocation, err) + } + fields.Number = number + supportCase, err := domain.NewSupportCase(fields) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - build validated case: %w", createLocation, err) + } + if err := repositories.SupportCases().Create(ctx, supportCase); err != nil { + if errors.Is(err, outbound.ErrSupportCaseConflict) { + return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict) + } + return createAttempt{}, fmt.Errorf("%s - store case: %w", createLocation, err) + } + return storeCreatedCase(ctx, unit, repositories, request, supportCase) +} + +func resolveManualAssessmentRubric( + ctx context.Context, + repositories outbound.SupportCaseRepositories, + fields *domain.NewSupportCaseInput, +) error { + if fields.Type != domain.SupportCaseTypeManualAssessment || fields.AssessmentTarget == nil { + return nil + } + rubric, err := repositories.SupportCaseRubrics().ResolveCurrent( + ctx, fields.AssessmentTarget.Specialization, fields.AssessmentTarget.Grade, + ) + if err != nil { + return fmt.Errorf("%s - resolve current manual assessment rubric: %w", createLocation, err) + } + if rubric == nil { + return nil + } + if rubric.Version < 1 || rubric.OpeningID == uuid.Nil || rubric.PolicyVersionID.IsZero() { + return fmt.Errorf("%s - rubric resolver returned an incomplete pin: %w", createLocation, domain.ErrInvalidSupportCase) + } + fields.RubricVersion = &rubric.Version + fields.RubricOpeningID = &rubric.OpeningID + fields.RubricPolicyID = &rubric.PolicyVersionID + return nil +} + +func storeReferenceFailure( + ctx context.Context, + unit outbound.UnitOfWork, + repositories outbound.SupportCaseRepositories, + request createRequest, + resolveErr error, +) (createAttempt, error) { + switch { + case errors.Is(resolveErr, ErrStateConflict): + return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict) + case errors.Is(resolveErr, outbound.ErrSupportCaseNotFound): + return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseNotFoundOutcome(), outbound.ErrSupportCaseNotFound) + default: + return createAttempt{}, resolveErr + } +} + +func storeCreatedCase( + ctx context.Context, + unit outbound.UnitOfWork, + repositories outbound.SupportCaseRepositories, + request createRequest, + supportCase domain.SupportCase, +) (createAttempt, error) { + outcome, err := domain.NewSupportCaseCreatedOutcome(supportCase) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - build create outcome: %w", createLocation, err) + } + if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil { + return createAttempt{}, fmt.Errorf("%s - store create outcome: %w", createLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) + } + result := CreateResult{Case: supportCase, TargetLate: supportCase.ResponseTarget().IsLate(request.now)} + return createAttempt{result: result}, nil +} + +func storeCreateFailure( + ctx context.Context, + unit outbound.UnitOfWork, + repositories outbound.SupportCaseRepositories, + request createRequest, + outcome domain.SupportCaseCreateOutcome, + responseErr error, +) (createAttempt, error) { + if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil { + return createAttempt{}, fmt.Errorf("%s - store failure outcome: %w", createLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) + } + return createAttempt{err: responseErr}, nil +} + +func replayCreateOutcome( + ctx context.Context, + repositories outbound.SupportCaseRepositories, + request createRequest, + stored outbound.IdempotencyRecord, +) (createAttempt, error) { + if stored.Fingerprint != request.fingerprint { + return createAttempt{err: ErrIdempotencyKeyReused}, nil + } + outcome, err := repositories.SupportCaseCreateOutcomes().GetCreateOutcome(ctx, request.scope) + if err != nil { + return createAttempt{}, fmt.Errorf("%s - read immutable create outcome: %w", createLocation, err) + } + switch outcome.Kind() { + case domain.SupportCaseCreateOutcomeCreated: + supportCase, ok := outcome.Case() + if !ok { + return createAttempt{}, fmt.Errorf("%s - restore immutable create outcome: %w", createLocation, domain.ErrInvalidSupportCase) + } + late, ok := outcome.CreationTargetWasLate() + if !ok { + return createAttempt{}, fmt.Errorf("%s - read original response target state: %w", createLocation, domain.ErrInvalidSupportCase) + } + return createAttempt{result: CreateResult{Case: supportCase, Replayed: true, TargetLate: late}}, nil + case domain.SupportCaseCreateOutcomeNotFound: + return createAttempt{err: outbound.ErrSupportCaseNotFound}, nil + case domain.SupportCaseCreateOutcomeStateConflict: + return createAttempt{err: ErrStateConflict}, nil + default: + return createAttempt{}, fmt.Errorf("%s - stored outcome kind is invalid: %w", createLocation, domain.ErrInvalidSupportCase) + } +} + +func newCaseInput( + command CreateCommand, + ownerID uuid.UUID, + responseTarget domain.SupportResponseTarget, + createdAt time.Time, +) domain.NewSupportCaseInput { + return domain.NewSupportCaseInput{ + OwnerID: ownerID, Type: command.Type, Description: command.Description, + Object: command.Object, AssessmentTarget: command.AssessmentTarget, + ComplaintReason: command.ComplaintReason, ResponseTarget: responseTarget, + CreatedAt: createdAt, + } +} + +func resolveReferences( + ctx context.Context, + unit outbound.UnitOfWork, + cases outbound.SupportCaseRepository, + attempts outbound.AssessmentAttemptRepository, + user domain.User, + input domain.NewSupportCaseInput, +) error { + object := input.Object + if object == nil { + return nil + } + switch object.Type { + case domain.SupportCaseObjectInvitation: + return outbound.ErrSupportCaseNotFound + case domain.SupportCaseObjectOrganization: + return resolveOrganizationReference(ctx, unit, user, object.ID) + case domain.SupportCaseObjectAssessmentAttempt: + return resolveAttemptReference(ctx, attempts, user, object.ID, input) + case domain.SupportCaseObjectSupportCase: + return resolveSupportCaseReference(ctx, cases, user, object.ID, input.Type) + default: + return outbound.ErrSupportCaseNotFound + } +} + +func resolveOrganizationReference(ctx context.Context, unit outbound.UnitOfWork, user domain.User, id uuid.UUID) error { + if user.Scenario != domain.ScenarioEmployer { + return outbound.ErrSupportCaseNotFound + } + if _, _, err := unit.Organizations().GetForMember(ctx, id, user.ID); err != nil { + if errors.Is(err, outbound.ErrOrganizationNotFound) { + return outbound.ErrSupportCaseNotFound + } + return fmt.Errorf("%s - resolve organization reference: %w", createLocation, err) + } + return nil +} + +func resolveAttemptReference( + ctx context.Context, + attempts outbound.AssessmentAttemptRepository, + user domain.User, + id uuid.UUID, + input domain.NewSupportCaseInput, +) error { + attempt, err := attempts.GetForCandidate(ctx, user.ID, domain.AssessmentAttemptID(id)) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return outbound.ErrSupportCaseNotFound + } + return fmt.Errorf("%s - resolve assessment attempt reference: %w", createLocation, err) + } + return validateAttemptReference(input, attempt) +} + +func resolveSupportCaseReference( + ctx context.Context, + cases outbound.SupportCaseRepository, + user domain.User, + id uuid.UUID, + caseType domain.SupportCaseType, +) error { + referenced, err := cases.GetOwned(ctx, user.ID, domain.SupportCaseID(id)) + if err != nil { + return err + } + if caseType != domain.SupportCaseTypeGradeAppeal { + return nil + } + decision := referenced.Decision() + if referenced.Type() != domain.SupportCaseTypeManualAssessment || + referenced.Status() != domain.SupportCaseStatusResolved || decision == nil || decision.Outcome() != domain.SupportCaseDecisionAssessed { + return ErrStateConflict + } + return nil +} + +func validateAttemptReference(input domain.NewSupportCaseInput, attempt domain.AssessmentAttempt) error { + switch input.Type { + case domain.SupportCaseTypeSupport, domain.SupportCaseTypeComplaint: + return nil + case domain.SupportCaseTypeManualAssessment: + target := input.AssessmentTarget + attemptSnapshot := attempt.Snapshot() + if target == nil || attemptSnapshot.Specialization == nil || *attemptSnapshot.Specialization != target.Specialization { + return ErrStateConflict + } + case domain.SupportCaseTypeGradeAppeal: + if attempt.State() != domain.AssessmentAttemptStateCompleted { + return ErrStateConflict + } + case domain.SupportCaseTypeAnticheatAppeal: + // Anti-cheat review decisions are not implemented. An owned attempt + // therefore has no appealable decision yet. + return ErrStateConflict + } + return nil +} + +func supportCaseRepositories( + unit outbound.UnitOfWork, +) (outbound.SupportCaseRepositories, outbound.AssessmentAttemptRepository, error) { + repositories, ok := unit.(outbound.SupportCaseRepositories) + if !ok { + return nil, nil, errors.New("supportcase.Service - unit of work does not expose support case repositories") + } + attempts, ok := unit.(outbound.AssessmentAttemptRepositories) + if !ok { + return nil, nil, errors.New("supportcase.Service - unit of work does not expose assessment attempts") + } + return repositories, attempts.AssessmentAttempts(), nil +} + +func requireAccount(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) (domain.User, error) { + user, err := unit.Users().GetByID(ctx, actorID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return domain.User{}, ErrForbidden + } + return domain.User{}, fmt.Errorf("%s - read account: %w", location, err) + } + if !user.EmailVerified() { + return domain.User{}, ErrEmailNotVerified + } + if user.Scenario != domain.ScenarioCandidate && user.Scenario != domain.ScenarioEmployer { + return domain.User{}, ErrForbidden + } + return user, nil +} + +func validIdempotencyKey(value string) bool { + if len(value) == 0 || len(value) > maxIdempotencyKeySize { + return false + } + for index := range len(value) { + character := value[index] + if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || + character >= '0' && character <= '9' || character == '.' || character == '_' || + character == ':' || character == '-' { + continue + } + return false + } + return true +} + +func canonicalCreateBody(command CreateCommand) ([]byte, error) { + var object any + if command.Object != nil { + object = []any{string(command.Object.Type), command.Object.ID.String()} + } + var target any + if command.AssessmentTarget != nil { + target = []any{string(command.AssessmentTarget.Specialization), string(command.AssessmentTarget.Grade)} + } + var reason any + if command.ComplaintReason != nil { + reason = string(*command.ComplaintReason) + } + return json.Marshal([]any{string(command.Type), command.Description, object, target, reason}) +} + +// RateLimitedError carries the server-computed Retry-After interval. +type RateLimitedError struct { + RetryAfter time.Duration +} + +func (RateLimitedError) Error() string { return ErrRateLimited.Error() } +func (RateLimitedError) Unwrap() error { return ErrRateLimited } + +// GetMyCase returns one full case only to its account owner. +func (service *Service) GetMyCase(ctx context.Context, actorID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) { + const location = "supportcase.Service.GetMyCase" + if actorID == uuid.Nil || caseID.IsZero() { + return domain.SupportCase{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrForbidden) + } + var result domain.SupportCase + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, err := requireAccount(ctx, unit, actorID, location); err != nil { + return err + } + repositories, _, err := supportCaseRepositories(unit) + if err != nil { + return err + } + result, err = repositories.SupportCases().GetOwned(ctx, actorID, caseID) + if err != nil { + return fmt.Errorf("%s - read owned case: %w", location, err) + } + return nil + }) + if err != nil { + return domain.SupportCase{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} + +// ListCommand selects one owner-scoped page. +type ListCommand struct { + ActorID uuid.UUID + After *outbound.SupportCaseListPosition + Limit int32 +} + +// ListMyCases returns summaries and never loads descriptions or history. +func (service *Service) ListMyCases(ctx context.Context, command ListCommand) (outbound.SupportCaseListPage, error) { + const location = "supportcase.Service.ListMyCases" + if command.ActorID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxSupportCasePageSize || + command.After != nil && (command.After.ID.IsZero() || command.After.CreatedAt.IsZero()) { + return outbound.SupportCaseListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidSupportCase) + } + var result outbound.SupportCaseListPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, err := requireAccount(ctx, unit, command.ActorID, location); err != nil { + return err + } + repositories, _, err := supportCaseRepositories(unit) + if err != nil { + return err + } + result, err = repositories.SupportCases().ListOwned(ctx, outbound.SupportCaseListQuery{ + OwnerID: command.ActorID, After: command.After, Limit: command.Limit, + }) + if err != nil { + return fmt.Errorf("%s - list owned cases: %w", location, err) + } + return nil + }) + if err != nil { + return outbound.SupportCaseListPage{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return result, nil +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 083d077..440cf16 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -428,9 +428,9 @@ The database enforces immutability. The trigger function `policy_versions_refuse Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature. -Open question for the attempt tasks: `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided. +The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization. -The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder. +Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 82cf1da..3c8e324 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -1,6 +1,6 @@ # Development -This guide describes the current technical scaffold and the commands declared in the repository. Product workflows remain planned; see [ARCHITECTURE.md](ARCHITECTURE.md) for the target design. +This guide describes implemented components and repository commands. Current business workflows are listed below; see [ARCHITECTURE.md](ARCHITECTURE.md) for the target design. ## Stack and version sources @@ -13,9 +13,9 @@ This guide describes the current technical scaffold and the commands declared in Select current stable frontend dependency releases and keep pnpm-lock.yaml committed for repeatable installs. ML dependencies are locked in uv.lock; Go dependencies are in backend/go.mod. An update must change its lock/configuration and pass checks for that service. Container images use the requested moving `latest` or `alpine` tags; inspect their current Compose/Dockerfile references instead of treating the tag as a fixed version. -## Scaffold status +## Implementation status -The repository contains a verifiable technical scaffold, not a product. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages. +MVP implementation is ongoing. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages. | Component | Pinned version | Source | | --- | --- | --- | @@ -51,13 +51,15 @@ What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap. - Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). -- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. +- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers). - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -The backend API implements registration, verification resend, and email confirmation. Frontend registration and confirmation screens, as well as login, remain placeholders. Other business flows, including HTTP consent management, profiles, the questionnaire and assessment, the company cabinet, needs, matching, invitations, contacts, product notifications, and support, are not implemented. The worker sends identity service mail through Resend; SMTP and product notification delivery are not implemented. `make -C deploy test-e2e` checks the SPA shell, API health, and error routes on a disposable stack, but not registration or email confirmation (see [TESTING.md](TESTING.md#browser-e2e-suite)). +The API and SPA implement registration, email confirmation, sign-in, consents, the private candidate profile and questionnaire, company profiles, needs, and account-owned support cases. The API also creates and resumes assessment attempts; answer submission and result calculation are not connected yet. Matching, invitations, contact disclosure, and product notification delivery remain in development. The worker sends identity service mail through Resend; SMTP is not implemented. Each workflow's boundaries are described in the [backend README](../../backend/README.en.md) and [frontend README](../../frontend/README.en.md). + +`make -C deploy test-e2e` checks the technical shell on a disposable stack. `make -C deploy test-e2e-registration` also exercises business workflows with an isolated local mail receiver and synthetic data; it does not prove real Resend delivery. See [TESTING.md](TESTING.md#browser-e2e-suite). ## Install and work loop @@ -86,9 +88,9 @@ Security tools have a separate install and work loop: `make -C security install` ### Sessions on local HTTP -The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production. +The session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production. -`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. A broader Origin check for other unsafe requests remains part of the session flow and is not implemented. The server does not use Host to derive an allowed Origin. +`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. The same check applies to other unsafe identity operations and protected session requests; the latter also require the session-bound CSRF token. The server does not use Host to derive an allowed Origin. ## Layout diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index f0d2ca1..e73b9cf 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -399,7 +399,9 @@ Unit tests (`make -C backend test`) check the profile rules without a database: The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged. -`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior/Go. The test-only `questionnaire-fixture` command reads the existing effective policy and publishes the required number of reviewed families before binding the catalog. It refuses existing backend bank ownership and is absent from ordinary and release images. The browser scenario covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled. +`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior with Go and Python. The test-only `questionnaire-fixture` command accepts only the unchanged initial demo policy, explicitly publishes `DemoProductPolicyV2`, then publishes the required number of reviewed families before binding the catalog. This also enables the support and assessment policy sections for browser tests. It refuses existing backend bank ownership or another current or scheduled policy and is absent from ordinary and release images. Normal startup still seeds V1 only. The browser scenario covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled. + +`assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training, offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration. ## Candidate visibility tests diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 7e4600a..7f44e56 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -428,9 +428,9 @@ Offsets и партиции. Каждый обработчик - один уча Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для применения квот организации); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот. -Открытый вопрос для задач попыток: `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено. +Решение для учета попыток MVP: `MaxAttemptsPerWindow` считает корневые попытки кандидата по всем специализациям в скользящем окне `AttemptWindow`. Корректирующая попытка использует место своего корня, учебная его не расходует. Таймеры пересдачи и повышения остаются независимыми по специализациям. -У документа `schema_version` 1 и разделы `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`; имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_bp`). Разбор строгий: отклоняются неизвестные поля, отсутствующие поля и null, неверные типы, дробные числа, значения вне int32, неизвестная версия схемы, данные после объекта и документы больше 64 KiB. Каноническая форма - компактная кодировка Go в порядке объявления полей. jsonb нормализует порядок ключей, поэтому `domain.RestorePolicyVersion` разбирает сохраненный документ, проверяет его, кодирует заново и сравнивает SHA-256 с `document_sha256`; при расхождении возвращается `domain.ErrPolicyDocumentIntegrity`. Golden-тест фиксирует каноническую форму, потому что ее изменение сломало бы проверку всех сохраненных версий; новой структуре нужны новая версия схемы и свой декодер. +Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются. Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 3f8e879..866005a 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -1,6 +1,6 @@ # Разработка -Эта страница описывает текущий технический каркас и команды, закрепленные в репозитории. Продуктовые сценарии остаются планом; подробная целевая архитектура находится в [ARCHITECTURE.md](ARCHITECTURE.md). +Эта страница описывает реализованные компоненты и команды репозитория. Текущие бизнес-сценарии перечислены ниже; целевая архитектура находится в [ARCHITECTURE.md](ARCHITECTURE.md). ## Стек и источники версий @@ -13,9 +13,9 @@ Frontend зависимости выбираются из актуальных stable releases; сохраняйте pnpm-lock.yaml для повторяемой установки. ML зависимости фиксируются в uv.lock, Go dependencies - в backend/go.mod. При обновлении меняйте соответствующий lock/config и запускайте checks области. Образы используют заданные moving `latest` или `alpine` tags; сверяйте ссылки в Compose/Dockerfiles и не считайте их стабильными номерами версии. -## Состояние каркаса +## Состояние реализации -В репозитории есть проверяемый технический каркас, а не готовый продукт. Значения ниже взяты из указанных файлов; при обновлении зависимости меняйте ее источник и lockfile, затем обновляйте эту таблицу на обоих языках. +Реализация MVP продолжается. Значения ниже взяты из указанных файлов; при обновлении зависимости меняйте ее источник и lockfile, затем обновляйте эту таблицу на обоих языках. | Компонент | Закрепленная версия | Источник | | --- | --- | --- | @@ -51,13 +51,15 @@ Frontend зависимости выбираются из актуальных s - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен. - Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). -- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. +- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий). - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Backend API реализует регистрацию, повторную отправку подтверждения и подтверждение email. Экраны регистрации и подтверждения во frontend, а также вход остаются заглушками. Другие бизнес-сценарии, включая HTTP управление согласиями, профили, анкету и тестирование, кабинет компании, потребности, подбор, приглашения, контакты, продуктовые уведомления и поддержку, не реализованы. Worker отправляет служебную почту identity через Resend; SMTP и отправка продуктовых уведомлений не реализованы. `make -C deploy test-e2e` проверяет оболочку SPA, API health и маршруты ошибок на одноразовом стеке, но не проверяет регистрацию или подтверждение email (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). +API и SPA реализуют регистрацию, подтверждение email, вход, согласия, личный профиль и анкету кандидата, профиль компании, потребности и собственные обращения в поддержку. API также создает и возобновляет попытки оценки; прием ответов и расчет результата пока не подключены. Подбор, приглашения, раскрытие контактов и отправка продуктовых уведомлений остаются в разработке. Worker отправляет служебную почту identity через Resend; SMTP не реализован. Границы каждого сценария описаны в [backend README](../../backend/README.md) и [frontend README](../../frontend/README.md). + +`make -C deploy test-e2e` проверяет техническую оболочку на одноразовом стеке. `make -C deploy test-e2e-registration` дополнительно проверяет бизнес-сценарии с изолированным локальным почтовым приемником и синтетическими данными; он не подтверждает доставку через реальный Resend. См. [TESTING.md](TESTING.md#браузерный-e2e-набор). ## Установка и цикл работы @@ -86,9 +88,9 @@ make check не является бизнес-E2E проверкой. make verif ### Сессии на локальном HTTP -Запланированная cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production. +Cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production. -`ConfirmEmail` требует, чтобы Origin точно совпадал с `APP_PUBLIC_URL`; отсутствующий Origin, буквальное значение `null` или другое значение дают 403 `csrf_check_failed`. Общая проверка Origin для остальных небезопасных запросов остается частью еще не реализованного потока сессий. Сервер не использует Host для определения разрешенного Origin. +`ConfirmEmail` требует, чтобы Origin точно совпадал с `APP_PUBLIC_URL`; отсутствующий Origin, буквальное значение `null` или другое значение дают 403 `csrf_check_failed`. Та же проверка действует для остальных небезопасных identity-операций и защищенных запросов сессии; последние также требуют привязанный к сессии CSRF-токен. Сервер не использует Host для определения разрешенного Origin. ## Структура diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 4f979fd..09e8c3e 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -399,7 +399,9 @@ Unit-тесты (`make -C backend test`) проверяют правила жу Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются. -`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior/Go. Тестовая команда `questionnaire-fixture` читает действующую политику и публикует необходимое число проверенных семейств перед привязкой каталога. Она отказывается работать поверх существующего backend-банка и отсутствует в обычном и релизном образах. Браузерный сценарий проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается. +`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior с Go и Python. Тестовая команда `questionnaire-fixture` принимает только неизмененную начальную демо-политику, явно публикует `DemoProductPolicyV2`, затем публикует необходимое число проверенных семейств перед привязкой каталога. Это также включает разделы политики поддержки и оценивания для браузерных тестов. Команда отказывается работать поверх существующего backend-банка или другой действующей либо запланированной политики и отсутствует в обычном и релизном образах. Обычный запуск по-прежнему создает только V1. Браузерный сценарий проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается. + +`assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим, отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки. ## Тесты видимости кандидата diff --git a/frontend/README.en.md b/frontend/README.en.md index f27c1b1..2ddded6 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -2,10 +2,10 @@ [Русский](README.md) | English -A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the manual candidate profile, and the company profile use the API. The cabinets share navigation and screen states; remaining business screens are connected as they are implemented. +A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The standalone results page, candidate directory, and employer invitations remain placeholders. - `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page. -- `src/pages/` holds public pages, sign-in and registration, consents, the company page, technical status, and remaining screen placeholders. +- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, company and employer needs pages, support cases, technical status, and remaining placeholders. - `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget. - `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)) and `company`; `src/features/` holds user actions and forms. - `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. @@ -17,13 +17,13 @@ From the repository root, `make -C frontend dev` starts development and `make -C ## Routes -| Group | Paths | Shell | -| --------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------- | -| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Candidate | `/candidate` and `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` | -| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` | +| Group | Paths | Shell | +| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | +| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | -Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. The server checks authorization again for every operation. +Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. `/support` sends a signed-in user to the support area for their account or to sign-in. Need pages pass `organization_id` in the query string, but the client checks the current owner directory and the server authorizes every request. `/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it. @@ -49,15 +49,31 @@ After saving, the form reloads the session and shows the account step returned b A 412 conflict retains the draft and offers explicit reload or replacement against the latest read version. Session errors hide private answers; responses from a previous account cannot repopulate the cache. Onboarding links follow the step returned by the server. `/candidate/questionnaire` is the destination for the saved questionnaire step. +## Candidate assessment + +`/candidate/assessment` reads availability and creates attempts through the API; `/candidate/assessment/:attemptId` resumes an attempt, submits answers, and finalizes it through server commands. Real assessment requires current C3 consent. `demo_express` is labeled as a demonstration and does not award a qualification score or confirmed category. The attempt screen displays the server result, but the separate `/candidate/results` route is still a placeholder; result history and confirmed category assignment are not implemented. The client does not calculate scores. + +The screen includes an informational notice about technical signals, but the browser does not yet collect or submit them. The server signal-ingest API exists separately; it is not connected to the UI. + +## Privacy settings + +`/candidate/privacy` currently shows consent management and a link to request manual assessment. Publication, search status, hidden organizations, preview, and history are available through the backend API, but a dedicated UI for these settings is not implemented. The employer candidate directory is also a placeholder; the server-side anonymous-card read API does not imply that this screen exists. + ## Company profile `pages/company` selects a company from the paginated active memberships of the current account. Only an owner may read or edit its profile. The form keeps its draft in memory, displays the server verification level without a promotion action, and builds its preview only from `candidate_card`. Creation uses one idempotency key for retries of the same body after a lost response. A 412 version conflict preserves the draft; the user explicitly loads current data, reviews the reapplied changes, and saves again. Background refresh does not reset the draft. A 401/403/404 response hides the profile and clears its cached query, then reloads the company directory. This complements server membership checks rather than replacing them. +## Employer needs + +`/employer/needs` shows a paginated list of organizations where the current account has an active owner membership and their needs. `/employer/needs/new?organization_id=...` creates a need, and `/employer/needs/:needId?organization_id=...` edits one. A URL or cached response grants no access: the client checks the current session and owner directory, and the server checks membership for every request. Cached data is scoped to the account and organization; a response from a prior session cannot populate the new cache. A 401/403/404 removes the organization's private queries. + +The editor draft stays in memory. Fields and skills extracted from the source remain suggestions with provenance until the user confirms, edits, or deletes them. Unknown values are not replaced with defaults. Readiness questions appear next to missing fields; recommendation status and categories come from the API, with no fabricated results. If a create response is uncertain, retry sends the unchanged body with the same idempotency key. A 412 conflict retains the draft, offers the latest version, and requires review of reapplied changes before another save. + ## Need entity -`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. The need UI is not implemented yet. +`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. Need pages and forms live in `pages/needs`, `pages/need-editor`, and `features/edit-need`. - `fromTransport` builds a draft from a `Need`. Each requirement field is an explicit state: `unknown` without a value, `extracted` as a stored suggestion with its provenance and quote, and `confirmed` as a confirmed value. An unknown field never becomes an empty string, an empty list, or a default value; a skill outside the taxonomy keeps `taxonomy_code: null`. Data that breaks the rule "value and source are null exactly when unknown" is rejected with `NeedTransportError`. - `toUpdateBody(need, draft)` sends only the fields whose request value changed, plus the `expected_version` of the read version. An untouched suggestion is not sent; when its field or list is sent for another reason, it goes with status `extracted`. A cleared field is sent as null, an emptied list as `[]`, and an untouched list is absent. @@ -67,6 +83,12 @@ Creation uses one idempotency key for retries of the same body after a lost resp The tests take their fixtures from the named contract examples in `api/core/openapi.bundle.yml` and check every body with the generated `NeedCreate` and `NeedUpdate` schemas. +## Support and manual assessment + +`/candidate/support/cases` and `/employer/support/cases` show each account's paginated support history. Their `.../new` routes create a case and `.../:caseId` routes show its status and history. The public `/support` route directs a signed-in user to their cabinet. The form draft stays in memory, and a retry of an unchanged request reuses its idempotency key. Support history is scoped to the current account and cleared when the session changes or the server denies access. + +Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The case page displays the status and rubric version returned by the server; the client does not create an outcome. + ## API client generation `make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values. diff --git a/frontend/README.md b/frontend/README.md index 8ebf3d7..d326b9c 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -2,10 +2,10 @@ Русский | [English](README.en.md) -SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, ручной профиль кандидата и профиль компании работают с API. Кабинеты имеют общую навигацию и состояния экранов; оставшиеся бизнес-экраны подключаются по мере реализации. +SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. Отдельная страница результатов, каталог кандидатов и приглашения остаются заготовками. - `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. -- `src/pages/` - публичные страницы, вход и регистрация, согласия, компания, технический статус и оставшиеся заготовки экранов. +- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, компания и потребности работодателя, обращения в поддержку, технический статус и оставшиеся заготовки экранов. - `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`. - `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)) и `company`; `src/features/` - действия пользователя и формы. - `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. @@ -17,13 +17,13 @@ SPA на React и TypeScript со сборкой Vite и структурой FS ## Маршруты -| Группа | Пути | Оболочка | -| ------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------------- | -| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` | -| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` | +| Группа | Пути | Оболочка | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | +| Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | -У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. Сервер повторно проверяет полномочия для каждой операции. +У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере. `/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает. @@ -49,15 +49,31 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Конфликт 412 сохраняет черновик и предлагает явное перечитывание или замену по последней прочитанной версии. Ошибки сессии скрывают приватные ответы; ответ прежнего аккаунта не заполняет кеш заново. Переходы onboarding следуют шагу, возвращенному сервером. Сохраненный шаг анкеты открывает `/candidate/questionnaire`. +## Проверка кандидата + +`/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. `demo_express` помечен как демонстрационный и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки, но отдельный маршрут `/candidate/results` пока остается заглушкой; история результатов и присвоение подтвержденных категорий не реализованы. Клиент не вычисляет баллы. + +На экране есть уведомление о технических сигналах, но браузер пока не собирает и не отправляет их. Серверный API приема сигналов существует отдельно; это не означает, что сигнализация подключена к интерфейсу. + +## Настройки приватности + +`/candidate/privacy` сейчас показывает управление согласиями и переход к запросу ручной оценки. Публикация карточки, статус поиска, список скрытых организаций, предпросмотр и история доступны через backend API, но отдельный интерфейс для этих настроек еще не реализован. Каталог кандидатов работодателя также остается заглушкой; наличие серверного API чтения анонимной карточки не означает наличия такого экрана. + ## Профиль компании `pages/company` выбирает компанию из постраничного списка действующих membership текущего аккаунта. Читать и менять профиль может только owner. Форма сохраняет черновик в памяти, показывает серверный уровень проверки без возможности повысить его и строит предпросмотр только из `candidate_card`. Создание использует один ключ идемпотентности для повторов того же тела после потерянного ответа. При конфликте версии 412 черновик сохраняется; пользователь отдельно загружает текущие данные, проверяет перенесенные изменения и повторяет сохранение. Фоновое обновление не сбрасывает черновик. Ответ 401/403/404 скрывает профиль и очищает его запрос из кеша; список компаний перечитывается. Это дополняет серверную проверку membership, а не заменяет ее. +## Потребности работодателя + +`/employer/needs` показывает постраничный список компаний, где у текущего аккаунта есть активная роль owner, и их потребности. `/employer/needs/new?organization_id=...` создает потребность, а `/employer/needs/:needId?organization_id=...` открывает ее для редактирования. URL и кеш не дают полномочий: клиент сверяет текущую сессию и каталог владельца, а сервер проверяет membership для каждого запроса. Данные кеша привязаны к аккаунту и компании; ответы предыдущей сессии не возвращаются в новый кеш. При 401/403/404 приватные запросы компании удаляются. + +Черновик редактора хранится в памяти. Извлеченные из описания поля и навыки остаются предложениями с происхождением, пока пользователь не подтвердит, не изменит или не удалит их. Неизвестные значения не подменяются дефолтами. Вопросы готовности показываются рядом с незаполненными полями; статус рекомендаций и категории берутся из API, без выдуманных результатов. Создание повторяет неизмененное тело с тем же ключом идемпотентности после неопределенного ответа. Конфликт версии 412 сохраняет черновик, предлагает загрузить актуальную версию и требует проверить перенесенные изменения до повтора. + ## Сущность потребности -`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. UI потребностей еще не реализован. +`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. Страницы и формы потребностей находятся в `pages/needs`, `pages/need-editor` и `features/edit-need`. - `fromTransport` строит черновик из `Need`. Каждое поле требования - явное состояние: `unknown` без значения, `extracted` - сохраненное предложение с происхождением и цитатой, `confirmed` - подтвержденное значение. Неизвестное поле никогда не превращается в пустую строку, пустой список или значение по умолчанию; навык вне таксономии сохраняет `taxonomy_code: null`. Данные, нарушающие правило "value и source равны null ровно при unknown", отклоняются ошибкой `NeedTransportError`. - `toUpdateBody(need, draft)` отправляет только поля, чье значение в запросе изменилось, и `expected_version` прочитанной версии. Нетронутое предложение не отправляется; если его поле или список отправляются по другой причине, оно уходит со статусом `extracted`. Очищенное поле уходит как null, опустошенный список - как `[]`, нетронутый список отсутствует. @@ -67,6 +83,12 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Тесты берут фикстуры из именованных примеров контракта в `api/core/openapi.bundle.yml` и проверяют каждое тело сгенерированными схемами `NeedCreate` и `NeedUpdate`. +## Поддержка и ручная оценка + +`/candidate/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе. + +Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Страница обращения показывает статус и сведения о версии рубрики, возвращенные сервером; результат не создается на клиенте. + ## Генерация API-клиента `make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения. diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts new file mode 100644 index 0000000..047d387 --- /dev/null +++ b/frontend/e2e/assessment.spec.ts @@ -0,0 +1,505 @@ +import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test"; + +type InboxMessage = { + text?: string; + html?: string; +}; + +type InboxResponse = { + messages: InboxMessage[]; +}; + +type AttemptSnapshot = { + id: string; + kind: "root" | "demo_express"; + current_item: { id: string; prompt: string } | null; + progress: { answered_items: number; max_items: number }; +}; + +const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1"; +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const password = "correct horse battery staple 2026"; + +test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" }); + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) + throw new Error("The local registration mailbox fixture is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as InboxResponse).messages; +} + +async function waitForVerificationMessage(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readInbox(email)).at(-1); + if (message) return message; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local registration mailbox did not receive the verification message."); +} + +function verificationToken(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The local registration message had no verification link."); + return token; +} + +async function registerVerifiedCandidate(page: Page): Promise { + const email = `assessment-${crypto.randomUUID()}@example.test`; + await page.goto("/register"); + await expect( + page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }), + ).toBeVisible(); + await expect(page.getByText(/C4/)).toHaveCount(0); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("radio", { name: /Кандидат/ }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const message = await waitForVerificationMessage(email); + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${verificationToken(message)}`; + await page.goto(verificationUrl.toString()); + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); + await expect.poll(() => page.evaluate(() => window.location.hash)).toBe(""); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + const confirmResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/email-verifications", + ); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + expect((await confirmResponse).status()).toBe(200); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto("/candidate/questionnaire"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await loginResponse).status()).toBe(201); +} + +async function grantC3(page: Page): Promise { + await page.goto("/candidate/privacy"); + await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); + await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); + const response = page.waitForResponse( + (item) => + item.request().method() === "PUT" && + new URL(item.url()).pathname === "/api/v1/me/consents/c3", + ); + await page.getByRole("button", { name: "Дать согласие C3" }).click(); + expect((await response).status()).toBe(200); +} + +async function saveAssessmentQuestionnaire(page: Page): Promise { + await page.goto("/candidate/questionnaire"); + await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByLabel("Моя оценка уровня").selectOption("junior"); + await page.getByRole("checkbox", { name: "Go", exact: true }).check(); + await page.getByRole("checkbox", { name: "Python", exact: true }).check(); + await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + const response = page.waitForResponse( + (item) => + item.request().method() === "PUT" && + new URL(item.url()).pathname === "/api/v1/me/questionnaire", + ); + await page.getByRole("button", { name: "Сохранить анкету" }).click(); + expect((await response).status()).toBe(200); +} + +async function focusWithKeyboard(page: Page, target: Locator): Promise { + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + for (let attempt = 0; attempt < 80; attempt += 1) { + await page.keyboard.press("Tab"); + if (await target.evaluate((element) => element === document.activeElement)) { + const visible = await target.evaluate((element) => { + if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false; + const style = getComputedStyle(element); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + expect(visible).toBe(true); + return; + } + } + throw new Error("Keyboard navigation did not reach the assessment action."); +} + +async function expectNoHorizontalOverflow(page: Page, width: number): Promise { + await page.setViewportSize({ width, height: 900 }); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(overflow, `no horizontal overflow at ${width}px`).toBe(false); +} + +async function navigateInApp(page: Page, path: string): Promise { + await page.evaluate((target) => { + window.history.pushState(window.history.state, "", target); + window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state })); + }, path); +} + +function attemptPath( + response: { url(): string; request(): { method(): string } }, + method: string, +): boolean { + return ( + response.request().method() === method && + /^\/api\/v1\/me\/assessment-attempts\/[^/]+$/.test(new URL(response.url()).pathname) + ); +} + +async function answerRequiredNumericItems( + page: Page, + attemptId: string, + itemCount: number, +): Promise { + let submitted = 0; + for (let sequence = 1; sequence <= itemCount; sequence += 1) { + await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible(); + const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await focusWithKeyboard(page, answerField); + await page.keyboard.type("1"); + + const answerResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`, + ); + const submitButton = page.getByRole("button", { name: "Отправить ответ" }); + await focusWithKeyboard(page, submitButton); + await page.keyboard.press("Enter"); + expect((await answerResponsePromise).status()).toBe(200); + submitted += 1; + } + return submitted; +} + +test("candidate can review, resume, and finish separate assessment modes", async ({ page }) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(120_000); + + await registerVerifiedCandidate(page); + await grantC3(page); + await saveAssessmentQuestionnaire(page); + + await page.goto("/candidate/assessment"); + await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); + await expect(page.getByText(/Метод:/)).toBeVisible(); + await expect(page.getByText("Лимит времени", { exact: true })).toBeVisible(); + await expect(page.getByText(/Камера, микрофон и запись экрана не используются/)).toBeVisible(); + await page.getByLabel("Язык задания").selectOption("python"); + await expect(page.getByLabel("Язык задания")).toHaveValue("python"); + await expectNoHorizontalOverflow(page, 360); + await expectNoHorizontalOverflow(page, 1280); + await expectNoHorizontalOverflow(page, 360); + + const createRealResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await page.getByRole("button", { name: "Начать полную проверку" }).click(); + const createRealResponse = await createRealResponsePromise; + expect(createRealResponse.status()).toBe(201); + expect(createRealResponse.request().postDataJSON()).toMatchObject({ + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "python", + }); + const realAttempt = (await createRealResponse.json()) as AttemptSnapshot; + expect(realAttempt.kind).toBe("root"); + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${realAttempt.id}$`)); + + const startRealResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`, + ); + const firstResume = page.getByRole("button", { name: "Начать или продолжить" }); + await focusWithKeyboard(page, firstResume); + await page.keyboard.press("Enter"); + const firstResumeResponse = await startRealResponsePromise; + expect(firstResumeResponse.status()).toBe(200); + const firstRealSnapshot = (await firstResumeResponse.json()) as AttemptSnapshot; + expect(firstRealSnapshot.current_item?.id).toBeTruthy(); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; + await expectNoHorizontalOverflow(page, 360); + await page.screenshot({ + path: `${artifactsDirectory}/assessment-attempt-360.png`, + animations: "disabled", + }); + await expectNoHorizontalOverflow(page, 1280); + await page.screenshot({ + path: `${artifactsDirectory}/assessment-attempt-1280.png`, + animations: "disabled", + }); + await expectNoHorizontalOverflow(page, 360); + + const reloadResponsePromise = page.waitForResponse((response) => attemptPath(response, "GET")); + await page.reload(); + const reloadedRealResponse = await reloadResponsePromise; + expect(reloadedRealResponse.status()).toBe(200); + const reloadedRealSnapshot = (await reloadedRealResponse.json()) as AttemptSnapshot; + expect(reloadedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id); + const resumeAgainPromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const resumeAgainResponse = await resumeAgainPromise; + expect(resumeAgainResponse.status()).toBe(200); + const resumedRealSnapshot = (await resumeAgainResponse.json()) as AttemptSnapshot; + expect(resumedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id); + + await expectNoHorizontalOverflow(page, 360); + expect(resumedRealSnapshot.progress.max_items).toBeGreaterThan(0); + expect(resumedRealSnapshot.progress.answered_items).toBe(0); + expect( + await answerRequiredNumericItems(page, realAttempt.id, resumedRealSnapshot.progress.max_items), + ).toBe(resumedRealSnapshot.progress.max_items); + await expect(page.getByRole("button", { name: "Завершить проверку" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Результат с сервера" })).toHaveCount(0); + + const finalizeRealResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${realAttempt.id}/finalize`, + ); + const resultResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "GET" && + response.status() === 200 && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${realAttempt.id}/result`, + ); + const finalizeRootButton = page.getByRole("button", { name: "Завершить проверку" }); + await focusWithKeyboard(page, finalizeRootButton); + await page.keyboard.press("Enter"); + expect((await finalizeRealResponsePromise).status()).toBe(200); + const resultResponse = await resultResponsePromise; + expect(resultResponse.status()).toBe(200); + expect(await resultResponse.json()).toMatchObject({ + attempt_id: realAttempt.id, + kind: "root", + task_language: "python", + }); + await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); + + await page.goto("/candidate/assessment"); + await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible(); + const createExpressResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await page.getByRole("button", { name: "Начать демонстрацию" }).click(); + const createExpressResponse = await createExpressResponsePromise; + expect(createExpressResponse.status()).toBe(201); + const expressAttempt = (await createExpressResponse.json()) as AttemptSnapshot; + expect(expressAttempt.kind).toBe("demo_express"); + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`)); + + const startExpressResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const startExpressResponse = await startExpressResponsePromise; + expect(startExpressResponse.status()).toBe(200); + const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot; + expect(firstExpressSnapshot.current_item?.id).toBeTruthy(); + + await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`); + await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Демонстрационная проверка" })).toHaveCount(0); + await navigateInApp(page, `/candidate/assessment/${expressAttempt.id}`); + await expect(page.getByRole("button", { name: "Начать или продолжить" })).toBeVisible(); + const resumedExpressResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const resumedExpressResponse = await resumedExpressResponsePromise; + expect(resumedExpressResponse.status()).toBe(200); + const resumedExpressSnapshot = (await resumedExpressResponse.json()) as AttemptSnapshot; + expect(resumedExpressSnapshot.current_item?.id).toBe(firstExpressSnapshot.current_item?.id); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + + const answerCommands: { key: string | undefined; body: string | null }[] = []; + const captureAnswerCommand = (request: Request) => { + if ( + request.method() !== "POST" || + new URL(request.url()).pathname !== + `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers` + ) { + return; + } + answerCommands.push({ + key: request.headers()["idempotency-key"], + body: request.postData(), + }); + }; + page.on("request", captureAnswerCommand); + await expectNoHorizontalOverflow(page, 360); + const numberAnswer = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await focusWithKeyboard(page, numberAnswer); + await numberAnswer.fill("1"); + const firstSubmitButton = page.getByRole("button", { name: "Отправить ответ" }); + await focusWithKeyboard(page, firstSubmitButton); + await page.context().setOffline(true); + await page.keyboard.press("Enter"); + await expect(page.getByRole("alert")).toContainText("Не удалось связаться с сервером"); + await expect.poll(() => answerCommands.length).toBe(1); + const offlineCommand = answerCommands[0]; + expect(offlineCommand?.key).toBeTruthy(); + await expect( + page.getByRole("button", { name: "Повторить отправку того же ответа" }), + ).toBeVisible(); + await page.context().setOffline(false); + + let forwardedResponses = 0; + await page.route("**/api/v1/me/assessment-attempts/*/answers", async (route: Route) => { + const response = await route.fetch(); + forwardedResponses += 1; + if (forwardedResponses === 1) { + await route.fulfill({ response, body: "{}" }); + return; + } + await route.fulfill({ response }); + }); + + const firstAnswerResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, + ); + await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click(); + expect((await firstAnswerResponsePromise).status()).toBe(200); + await expect(page.getByRole("alert")).toBeVisible(); + const retryResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, + ); + const savedAfterAnswerPromise = page.waitForResponse( + (response) => + response.request().method() === "GET" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`, + ); + await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click(); + expect((await retryResponsePromise).status()).toBe(200); + const savedAfterAnswer = await savedAfterAnswerPromise; + expect(savedAfterAnswer.status()).toBe(200); + const savedAfterAnswerSnapshot = (await savedAfterAnswer.json()) as AttemptSnapshot; + expect(savedAfterAnswerSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id); + expect(savedAfterAnswerSnapshot.progress.answered_items).toBe(1); + expect(answerCommands).toHaveLength(3); + expect(answerCommands[0]?.key).toBeTruthy(); + expect(answerCommands[1]?.key).toBe(answerCommands[0]?.key); + expect(answerCommands[1]?.body).toBe(answerCommands[0]?.body); + expect(answerCommands[2]?.key).toBe(answerCommands[0]?.key); + expect(answerCommands[2]?.body).toBe(answerCommands[0]?.body); + await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); + + await page.unroute("**/api/v1/me/assessment-attempts/*/answers"); + const expressReloadResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "GET" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`, + ); + await page.reload(); + const expressReloadResponse = await expressReloadResponsePromise; + expect(expressReloadResponse.status()).toBe(200); + const reloadedExpressSnapshot = (await expressReloadResponse.json()) as AttemptSnapshot; + expect(reloadedExpressSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id); + expect(reloadedExpressSnapshot.progress.answered_items).toBe(1); + const resumeSavedProgressPromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const resumeSavedProgressResponse = await resumeSavedProgressPromise; + expect(resumeSavedProgressResponse.status()).toBe(200); + const resumedExpressProgress = (await resumeSavedProgressResponse.json()) as AttemptSnapshot; + expect(resumedExpressProgress.current_item?.id).toBe(reloadedExpressSnapshot.current_item?.id); + expect(resumedExpressProgress.progress.answered_items).toBe(1); + await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); + + for (const sequence of [2, 3]) { + const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await focusWithKeyboard(page, answerField); + await page.keyboard.type("1"); + const answerResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, + ); + const submitButton = page.getByRole("button", { name: "Отправить ответ" }); + await focusWithKeyboard(page, submitButton); + await page.keyboard.press("Enter"); + expect((await answerResponsePromise).status()).toBe(200); + if (sequence < 3) + await expect(page.getByRole("heading", { name: `Задание ${sequence + 1}` })).toBeVisible(); + } + + const finalizeResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/assessment-attempts/${expressAttempt.id}/finalize`, + ); + const finalizeButton = page.getByRole("button", { name: "Завершить проверку" }); + await focusWithKeyboard(page, finalizeButton); + await page.keyboard.press("Enter"); + expect((await finalizeResponsePromise).status()).toBe(200); + await expect( + page.getByText( + "Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.", + ), + ).toBeVisible(); + await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0); + page.off("request", captureAnswerCommand); +}); diff --git a/frontend/e2e/company-management.spec.ts b/frontend/e2e/company-management.spec.ts index d1673ab..8e24ccc 100644 --- a/frontend/e2e/company-management.spec.ts +++ b/frontend/e2e/company-management.spec.ts @@ -294,6 +294,12 @@ test.describe("company cabinet", () => { new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` && response.status() === 412, ); + const csrfFailureResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "PATCH" && + new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` && + response.status() === 403, + ); const refreshedSessionPromise = page.waitForResponse( (response) => response.request().method() === "GET" && @@ -301,6 +307,8 @@ test.describe("company cabinet", () => { response.status() === 200, ); await page.getByRole("button", { name: "Сохранить изменения" }).click(); + const csrfFailureResponse = await csrfFailureResponsePromise; + expect(await csrfFailureResponse.json()).toMatchObject({ code: "csrf_check_failed" }); await expect(page.getByRole("alert")).toContainText("Проверка входа обновлена"); await refreshedSessionPromise; await expect(page.getByLabel("Название компании")).toHaveValue(updatedName); diff --git a/frontend/e2e/need-management.spec.ts b/frontend/e2e/need-management.spec.ts new file mode 100644 index 0000000..1f99996 --- /dev/null +++ b/frontend/e2e/need-management.spec.ts @@ -0,0 +1,558 @@ +import { expect, test, type Locator, type Page, type Response } from "@playwright/test"; + +type InboxMessage = { + id: string; + text?: string; + html?: string; +}; + +type InboxResponse = { + messages: InboxMessage[]; +}; + +type CurrentSessionResponse = { + account: { id: string }; +}; + +type OrganizationResponse = { + id: string; + name: string; +}; + +type NeedResponse = { + id: string; + title: string; + source_text?: string | null; + version: number; + requirements_version: number; + requirements: { + specialization: { status: string; value: string | null; source?: { origin: string } | null }; + required_skills: { + name: string; + status: string; + source?: { origin: string } | null; + }[]; + tasks: { text: string; status: string; source?: { origin: string } | null }[]; + grade: { + status: string; + value: string | null; + source?: { origin: string } | null; + }; + salary: { + status: string; + value: { tax_basis: string } | null; + source?: { origin: string } | null; + }; + }; + readiness: { status: string; missing_fields: { field: string; question: string }[] }; + recommendations: { status: string; categories: unknown[] }; +}; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1"; +const password = "correct horse battery staple 2026"; + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local browser test origin is not configured."); + return value; +} + +function needCollectionPath(organizationId: string): string { + return `/api/v1/organizations/${organizationId}/needs`; +} + +function needPath(organizationId: string, needId: string): string { + return `${needCollectionPath(organizationId)}/${needId}`; +} + +async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) + throw new Error("The local registration mailbox fixture is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as InboxResponse).messages; +} + +async function waitForVerificationMessage(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readInbox(email)).at(-1); + if (message) return message; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local registration mailbox did not receive the expected message."); +} + +function verificationToken(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The local registration message had no verification link."); + return token; +} + +async function registerVerifiedEmployer(page: Page): Promise<{ email: string; userId: string }> { + const email = `company-${crypto.randomUUID().slice(0, 8)}@example.test`; + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("radio", { name: /Работодатель/ }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const message = await waitForVerificationMessage(email); + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${verificationToken(message)}`; + await page.goto(verificationUrl.toString()); + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto("/employer/company"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.status() === 201, + ); + await page.getByRole("button", { name: "Войти" }).click(); + await expect(page.getByRole("heading", { name: "Компания" })).toBeVisible(); + const loginResponse = await loginResponsePromise; + const currentSession = (await loginResponse.json()) as CurrentSessionResponse; + return { email, userId: currentSession.account.id }; +} + +async function signInEmployer(page: Page, email: string): Promise { + await page.goto("/employer/needs"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponsePromise = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.status() === 201, + ); + await page.getByRole("button", { name: "Войти" }).click(); + await loginResponsePromise; +} + +async function createOrganization(page: Page, name: string): Promise { + const result = await page.evaluate( + async ({ organizationName, key }) => { + const sessionResponse = await fetch("/api/v1/identity/sessions/current", { + cache: "no-store", + }); + if (!sessionResponse.ok) return { status: sessionResponse.status, body: null }; + const session = (await sessionResponse.json()) as { csrf_token?: string }; + if (!session.csrf_token) return { status: 401, body: null }; + const response = await fetch("/api/v1/organizations", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Idempotency-Key": key, + "X-CSRF-Token": session.csrf_token, + }, + body: JSON.stringify({ name: organizationName }), + }); + return { + status: response.status, + body: (await response.json()) as OrganizationResponse, + }; + }, + { organizationName: name, key: crypto.randomUUID() }, + ); + if (result.status !== 201 || !result.body) { + throw new Error("Could not create the synthetic organization for the need flow."); + } + return result.body; +} + +async function revokeMembership( + organizationId: string, + userId: string, + successorUserId: string, +): Promise { + const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL; + const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN; + if (!fixtureURL || !fixtureToken) + throw new Error("The isolated company fixture is not configured."); + const response = await fetch(new URL(fixtureURL), { + method: "POST", + headers: { + Authorization: `Bearer ${fixtureToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + organization_id: organizationId, + user_id: userId, + successor_user_id: successorUserId, + }), + }); + if (response.status !== 204) { + throw new Error( + `The isolated company fixture could not transfer the synthetic membership (status ${response.status}).`, + ); + } +} + +async function findSkillRow(section: Locator, name: string): Promise { + const rows = section.getByRole("listitem"); + for (let index = 0; index < (await rows.count()); index += 1) { + const row = rows.nth(index); + if ((await row.locator("input").inputValue()) === name) return row; + } + throw new Error(`The parsed need did not contain the expected skill ${name}.`); +} + +function isResponse(response: Response, method: string, path: string, status: number): boolean { + return ( + response.request().method() === method && + new URL(response.url()).pathname === path && + response.status() === status + ); +} + +function sanitizedPageError(error: Error, privateValues: string[]): string { + let message = error.message.split("\n", 1)[0] ?? ""; + for (const value of privateValues) { + if (value !== "") message = message.replaceAll(value, "[redacted]"); + } + message = message + .replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[email]") + .replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, "[id]"); + return `${error.name}: ${message.slice(0, 180)}`; +} + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +test.describe("employer needs", () => { + test.skip( + !mailFixtureEnabled || !companyFixtureEnabled, + "Requires the isolated mail and company fixtures.", + ); + + test("creates, edits, reloads, handles conflicts, and removes private data after owner access ends", async ({ + browser, + page, + }) => { + const owner = await registerVerifiedEmployer(page); + const suffix = crypto.randomUUID().slice(0, 8); + const organization = await createOrganization(page, `Need team ${suffix}`); + const sourceText = + "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."; + const pageErrors: string[] = []; + page.on("pageerror", (error) => { + pageErrors.push(sanitizedPageError(error, [owner.email, sourceText, suffix])); + }); + + await page.goto(`/employer/needs?organization_id=${encodeURIComponent(organization.id)}`); + await expect( + page.getByRole("status").getByText("Потребностей пока нет", { exact: true }), + ).toBeVisible(); + await page.getByRole("link", { name: "Создать потребность" }).first().click(); + await expect(page.getByLabel("Название потребности")).toBeVisible(); + await expect(page.getByText("Вакансия для сохранения потребности не требуется.")).toBeVisible(); + await expect(page.getByLabel("Грейд")).toHaveValue(""); + await expect(page.getByLabel("База суммы")).toHaveValue(""); + await expect( + page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."), + ).toBeVisible(); + await page.getByLabel("Название потребности").fill(`Payments backend ${suffix}`); + expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]); + await page.getByLabel("Описание работы").fill(sourceText); + expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]); + + const organizationNeedsPath = needCollectionPath(organization.id); + const createResponsePromise = page.waitForResponse((response) => + isResponse(response, "POST", organizationNeedsPath, 201), + ); + await page.getByRole("button", { name: "Создать потребность" }).click(); + const createResponse = await createResponsePromise; + const createRequest = createResponse.request(); + expect(createRequest.headers()["x-csrf-token"]).toBeTruthy(); + expect(createRequest.headers()["idempotency-key"]).toBeTruthy(); + const created = (await createResponse.json()) as NeedResponse; + expect(created.version).toBe(1); + expect(created.requirements_version).toBe(1); + expect(created.requirements.grade.status).toBe("unknown"); + expect(created.requirements.grade.value).toBeNull(); + expect(created.readiness.missing_fields.map((field) => field.field)).toContain("salary"); + expect(created.recommendations.status).toBe("not_available"); + + const requiredSkills = page + .getByRole("heading", { name: "Обязательные навыки" }) + .locator("xpath=.."); + await expect(requiredSkills.getByRole("listitem")).toHaveCount(3); + const goRow = await findSkillRow(requiredSkills, "Go"); + const postgresRow = await findSkillRow(requiredSkills, "PostgreSQL"); + const temporalRow = await findSkillRow(requiredSkills, "Temporal"); + await goRow.getByRole("button", { name: "Подтвердить", exact: true }).click(); + await temporalRow.locator("input").fill("TemporalDB"); + await postgresRow.getByRole("button", { name: "Удалить", exact: true }).click(); + + const needId = created.id; + const itemPath = needPath(organization.id, needId); + const firstSavePromise = page.waitForResponse((response) => + isResponse(response, "PATCH", itemPath, 200), + ); + await page.getByRole("button", { name: "Сохранить изменения" }).click(); + const firstSave = (await firstSavePromise).json() as Promise; + const saved = await firstSave; + expect(saved.version).toBe(2); + expect(saved.requirements.required_skills.map((skill) => skill.name)).toEqual([ + "Go", + "TemporalDB", + ]); + expect(saved.recommendations.status).toBe("pending"); + expect(saved.recommendations.categories).toEqual([]); + await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible(); + + const reloadResponsePromise = page.waitForResponse((response) => + isResponse(response, "GET", itemPath, 200), + ); + await page.reload(); + const reloaded = (await reloadResponsePromise).json() as Promise; + const reloadedNeed = await reloaded; + expect(reloadedNeed.requirements.required_skills.map((skill) => skill.name)).not.toContain( + "PostgreSQL", + ); + await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText); + await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible(); + + const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + const secondPage = await secondContext.newPage(); + try { + await signInEmployer(secondPage, owner.email); + await secondPage.goto( + `/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`, + ); + await expect(secondPage.getByLabel("Название потребности")).toHaveValue( + `Payments backend ${suffix}`, + ); + + const firstWindowTitle = `Payments backend first ${suffix}`; + await page.getByLabel("Название потребности").fill(firstWindowTitle); + const firstWindowSave = page.waitForResponse((response) => + isResponse(response, "PATCH", itemPath, 200), + ); + await page.getByRole("button", { name: "Сохранить изменения" }).click(); + const firstWindowResponse = await firstWindowSave; + const firstWindowSaved = (await firstWindowResponse.json()) as NeedResponse; + expect(firstWindowSaved.title).toBe(firstWindowTitle); + await expect(page.getByLabel("Название потребности")).toHaveValue(firstWindowTitle); + + const secondWindowDraft = `Payments backend second ${suffix}`; + await secondPage.getByLabel("Название потребности").fill(secondWindowDraft); + const conflictResponsePromise = secondPage.waitForResponse((response) => + isResponse(response, "PATCH", itemPath, 412), + ); + await secondPage.getByRole("button", { name: "Сохранить изменения" }).click(); + expect((await conflictResponsePromise).status()).toBe(412); + await expect(secondPage.getByRole("heading", { name: "Версия изменилась" })).toBeVisible(); + await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft); + + const latestResponsePromise = secondPage.waitForResponse((response) => + isResponse(response, "GET", itemPath, 200), + ); + await secondPage.getByRole("button", { name: "Загрузить и применить мой черновик" }).click(); + await latestResponsePromise; + await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft); + await expect( + secondPage.getByRole("heading", { name: "Проверьте объединенный черновик" }), + ).toBeVisible(); + await secondPage.getByRole("button", { name: "Продолжить сохранение" }).click(); + const rebasedSavePromise = secondPage.waitForResponse((response) => + isResponse(response, "PATCH", itemPath, 200), + ); + await secondPage.getByRole("button", { name: "Сохранить изменения" }).click(); + const rebasedSaveResponse = await rebasedSavePromise; + const rebased = (await rebasedSaveResponse.json()) as NeedResponse; + expect(rebased.title).toBe(secondWindowDraft); + await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft); + + const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; + await page.setViewportSize({ width: 360, height: 900 }); + const hasHorizontalOverflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(hasHorizontalOverflow).toBe(false); + await page.screenshot({ + path: `${artifactsDirectory}/need-editor-mobile.png`, + animations: "disabled", + }); + await page.setViewportSize({ width: 1280, height: 900 }); + await page.screenshot({ + path: `${artifactsDirectory}/need-editor-desktop.png`, + animations: "disabled", + }); + + const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + try { + const successorPage = await successorContext.newPage(); + const successor = await registerVerifiedEmployer(successorPage); + await successorPage.goto( + `/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`, + ); + await expect( + successorPage.getByText("Потребность недоступна", { exact: true }), + ).toBeVisible(); + await expect(successorPage.getByLabel("Название потребности")).toHaveCount(0); + const beforeTransferStatus = await successorPage.evaluate( + async ({ orgId, id }) => { + const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, { + cache: "no-store", + }); + return response.status; + }, + { orgId: organization.id, id: needId }, + ); + expect(beforeTransferStatus).toBe(404); + + await revokeMembership(organization.id, owner.userId, successor.userId); + + async function expectOwnerAccessRemoved(targetPage: Page): Promise { + await test.step("Refresh directory after owner access is revoked", async () => { + const directoryResponsePromise = targetPage.waitForResponse( + (response) => + response.request().method() === "GET" && + new URL(response.url()).pathname === "/api/v1/me/organizations" && + response.status() === 200, + { timeout: 10_000 }, + ); + await targetPage.bringToFront(); + await targetPage.evaluate(() => { + window.dispatchEvent(new Event("visibilitychange")); + }); + await directoryResponsePromise; + await expect( + targetPage.getByText("Потребность недоступна", { exact: true }), + ).toBeVisible(); + await expect(targetPage.getByLabel("Название потребности")).toHaveCount(0); + await expect(targetPage.getByLabel("Описание работы")).toHaveCount(0); + await expect(targetPage.getByText(sourceText, { exact: true })).toHaveCount(0); + }); + } + + await expectOwnerAccessRemoved(page); + await expectOwnerAccessRemoved(secondPage); + const revokedStatus = await page.evaluate( + async ({ orgId, id }) => { + const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, { + cache: "no-store", + }); + return response.status; + }, + { orgId: organization.id, id: needId }, + ); + expect(revokedStatus).toBe(404); + + const successorNeedResponse = successorPage.waitForResponse((response) => + isResponse(response, "GET", itemPath, 200), + ); + await successorPage.goto( + `/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`, + ); + await successorNeedResponse; + await expect(successorPage.getByLabel("Название потребности")).toHaveValue( + secondWindowDraft, + ); + } finally { + await successorContext.close(); + } + } finally { + await secondContext.close(); + } + }); + + test("creates a manual need without source text and keeps recommendations pending", async ({ + page, + }) => { + await registerVerifiedEmployer(page); + const suffix = crypto.randomUUID().slice(0, 8); + const organization = await createOrganization(page, `Manual need ${suffix}`); + const collectionPath = needCollectionPath(organization.id); + await page.goto(`/employer/needs/new?organization_id=${encodeURIComponent(organization.id)}`); + await expect(page.getByLabel("Название потребности")).toBeVisible(); + await page.getByLabel("Название потребности").fill(`Manual Go developer ${suffix}`); + await expect(page.getByLabel("Описание работы")).toHaveValue(""); + await page.getByLabel("Специализация").selectOption("backend"); + await page.getByLabel("Грейд").selectOption("junior"); + + const requiredSkills = page + .getByRole("heading", { name: "Обязательные навыки" }) + .locator("xpath=.."); + await requiredSkills.getByLabel("Добавить навык").fill("Go"); + await requiredSkills.getByRole("button", { name: "Добавить", exact: true }).click(); + const tasks = page.getByRole("heading", { name: "Задачи команды" }).locator("xpath=.."); + await tasks.getByLabel("Добавить задачу").fill("Развивать сервис уведомлений"); + await tasks.getByRole("button", { name: "Добавить", exact: true }).click(); + await page.getByLabel("От, рублей в месяц").fill("100000"); + await page.getByLabel("До, рублей в месяц").fill("130000"); + await page.getByLabel("База суммы").selectOption("net"); + + const createResponsePromise = page.waitForResponse((response) => + isResponse(response, "POST", collectionPath, 201), + ); + await page.getByRole("button", { name: "Создать потребность" }).click(); + const createResponse = await createResponsePromise; + const createBody = createResponse.request().postDataJSON() as Record; + expect(createBody).not.toHaveProperty("source_text"); + expect(createBody).not.toHaveProperty("vacancy_id"); + const created = (await createResponse.json()) as NeedResponse; + expect(created.source_text).toBeNull(); + expect(created.requirements.specialization).toMatchObject({ + status: "confirmed", + value: "backend", + source: { origin: "manual" }, + }); + expect(created.requirements.grade).toMatchObject({ + status: "confirmed", + value: "junior", + source: { origin: "manual" }, + }); + expect(created.requirements.required_skills).toHaveLength(1); + expect(created.requirements.required_skills[0]).toMatchObject({ + name: "Go", + status: "confirmed", + source: { origin: "manual" }, + }); + expect(created.requirements.tasks).toHaveLength(1); + expect(created.requirements.tasks[0]).toMatchObject({ + text: "Развивать сервис уведомлений", + status: "confirmed", + source: { origin: "manual" }, + }); + expect(created.requirements.salary).toMatchObject({ + status: "confirmed", + value: { tax_basis: "net" }, + source: { origin: "manual" }, + }); + expect(created.recommendations).toMatchObject({ status: "pending", categories: [] }); + expect(created.readiness.status).toBe("incomplete"); + await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible(); + + const detailPath = needPath(organization.id, created.id); + const reloadResponsePromise = page.waitForResponse((response) => + isResponse(response, "GET", detailPath, 200), + ); + await page.reload(); + const reloadResponse = await reloadResponsePromise; + const persisted = (await reloadResponse.json()) as NeedResponse; + expect(persisted.source_text).toBeNull(); + expect(persisted.requirements.grade.source?.origin).toBe("manual"); + expect(persisted.requirements.required_skills[0]?.source?.origin).toBe("manual"); + expect(persisted.requirements.salary.source?.origin).toBe("manual"); + expect(persisted.recommendations).toMatchObject({ status: "pending", categories: [] }); + await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible(); + }); +}); diff --git a/frontend/e2e/support-cases.spec.ts b/frontend/e2e/support-cases.spec.ts new file mode 100644 index 0000000..e930d08 --- /dev/null +++ b/frontend/e2e/support-cases.spec.ts @@ -0,0 +1,445 @@ +import { expect, test, type Locator, type Page } from "@playwright/test"; + +type InboxMessage = { + id: string; + text?: string; + html?: string; +}; + +type InboxResponse = { + messages: InboxMessage[]; +}; + +type SupportCaseResponse = { + id: string; + number: string; + type: string; + status: string; + description: string; + assessment_target: { specialization: string; grade: string } | null; + rubric_version: number | null; + response_target: { business_days: number; kind: string; due_at: string }; + decision: unknown; +}; + +type SupportCaseListResponse = { + items: Pick[]; +}; + +type ConsentList = { + items: { purpose: string; state: string }[]; +}; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1"; +const testPassword = "correct horse battery staple 2026"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +function baseURL(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as InboxResponse).messages; +} + +async function waitForVerificationMessage(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readInbox(email)).at(-1); + if (message) return message; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local registration mailbox did not receive the verification message."); +} + +function tokenFromMessage(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The local registration message had no verification link."); + return token; +} + +async function registerCandidate(page: Page, prefix: string): Promise { + const email = `${prefix}-${crypto.randomUUID()}@example.test`; + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(testPassword); + await page.getByRole("radio", { name: /Кандидат/ }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const message = await waitForVerificationMessage(email); + const verificationUrl = new URL("/verify-email", baseURL()); + verificationUrl.hash = `token=${tokenFromMessage(message)}`; + await page.goto(verificationUrl.toString()); + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); + expect(await page.evaluate(() => window.location.hash)).toBe(""); + await page.getByLabel("Пароль, выбранный при регистрации").fill(testPassword); + const confirmation = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/email-verifications" && + response.request().method() === "POST", + ); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + expect((await confirmation).status()).toBe(200); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto("/login"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(testPassword); + const login = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.request().method() === "POST", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await login).status()).toBe(201); + return email; +} + +async function replaySupportCaseCreate( + page: Page, + originalResponse: Awaited>, +): Promise { + const originalRequest = originalResponse.request(); + const body = originalRequest.postData(); + const idempotencyKey = originalRequest.headers()["idempotency-key"]; + expect(body).toBeTruthy(); + expect(idempotencyKey).toBeTruthy(); + + const replay = await page.evaluate( + async ({ body, idempotencyKey }) => { + const sessionResponse = await fetch("/api/v1/identity/sessions/current", { + credentials: "include", + }); + if (!sessionResponse.ok) throw new Error("Could not read the current local session."); + const session = (await sessionResponse.json()) as { csrf_token?: string }; + if (!session.csrf_token) throw new Error("The current local session has no CSRF token."); + + const response = await fetch("/api/v1/me/support-cases", { + method: "POST", + credentials: "include", + headers: { + "Content-Type": "application/json", + "Idempotency-Key": idempotencyKey, + "X-CSRF-Token": session.csrf_token, + }, + body, + }); + return { + status: response.status, + body: (await response.json()) as SupportCaseResponse, + }; + }, + { body: body ?? "", idempotencyKey: idempotencyKey ?? "" }, + ); + + expect(replay.status).toBe(201); + return replay.body; +} + +async function focusByKeyboard(page: Page, target: Locator): Promise { + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + for (let attempt = 0; attempt < 80; attempt += 1) { + await page.keyboard.press("Tab"); + if (await target.evaluate((element) => element === document.activeElement)) { + const hasVisibleFocus = await target.evaluate((element) => { + if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false; + const style = getComputedStyle(element); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + expect(hasVisibleFocus).toBe(true); + return; + } + } + throw new Error("Keyboard navigation did not reach the requested control."); +} + +async function checkResponsiveForm( + page: Page, + target: Locator, + widths = [360, 768, 1280], +): Promise { + for (const width of widths) { + await page.setViewportSize({ width, height: 900 }); + await focusByKeyboard(page, target); + const hasHorizontalOverflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false); + } +} + +test.describe("candidate support cases and manual assessment", () => { + test.skip( + !mailFixtureEnabled || !questionnaireFixtureEnabled, + "Requires the isolated local mail and published-bank fixtures.", + ); + + test("creates and reloads a support case from an unavailable assessment and hides it from another account", async ({ + page, + }) => { + await registerCandidate(page, "support-author"); + await page.goto("/candidate/assessment"); + await expect(page.getByRole("link", { name: "Поддержка", exact: true })).toBeVisible(); + await page.getByRole("link", { name: "Поддержка", exact: true }).click(); + await expect(page).toHaveURL(/\/candidate\/support\/cases$/); + await page.getByRole("link", { name: "Написать в поддержку" }).click(); + await expect(page).toHaveURL(/\/candidate\/support\/cases\/new$/); + + const description = "Не удается открыть оценку для выбранной категории."; + const textarea = page.getByLabel("Что произошло или какая помощь нужна"); + await textarea.fill(description); + await checkResponsiveForm(page, textarea); + + await page.setViewportSize({ width: 360, height: 900 }); + const submitButton = page.getByRole("button", { name: "Отправить обращение" }); + await focusByKeyboard(page, submitButton); + const createResponsePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/support-cases" && + response.request().method() === "POST", + ); + await page.keyboard.press("Enter"); + const createResponse = await createResponsePromise; + expect(createResponse.status()).toBe(201); + const createBody = createResponse.request().postDataJSON() as Record; + expect(createBody).toMatchObject({ type: "support", description }); + expect("assessment_target" in createBody).toBe(false); + const created = (await createResponse.json()) as SupportCaseResponse; + expect(created.type).toBe("support"); + expect(created.description).toBe(description); + expect(created.response_target.kind).toBe("operational_goal"); + + const casePath = `/candidate/support/cases/${created.id}`; + await expect(page).toHaveURL(new RegExp(`${created.id}$`)); + await expect(page.getByText(description, { exact: true })).toBeVisible(); + await expect(page.getByText("Операционная цель", { exact: true })).toBeVisible(); + await expect(page.getByText(/рабочих дней/)).toBeVisible(); + + const detailResponsePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` && + response.request().method() === "GET", + ); + await page.reload(); + expect((await detailResponsePromise).status()).toBe(200); + await expect(page.getByText(description, { exact: true })).toBeVisible(); + const replayed = await replaySupportCaseCreate(page, createResponse); + expect(replayed.id).toBe(created.id); + const supportList = await page.evaluate(async () => { + const response = await fetch("/api/v1/me/support-cases?limit=100", { + credentials: "include", + }); + if (!response.ok) throw new Error("Could not read the local support case list."); + return (await response.json()) as SupportCaseListResponse; + }); + expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1); + await page.getByRole("link", { name: "Мои обращения" }).click(); + await expect(page.getByRole("link", { name: created.number })).toBeVisible(); + + const logoutStatus = await page.evaluate(async () => { + const current = await fetch("/api/v1/identity/sessions/current", { + credentials: "include", + }); + if (!current.ok) return current.status; + const session = (await current.json()) as { csrf_token?: string }; + if (!session.csrf_token) return 0; + const response = await fetch("/api/v1/identity/sessions/current", { + method: "DELETE", + credentials: "include", + headers: { "X-CSRF-Token": session.csrf_token }, + }); + return response.status; + }); + expect(logoutStatus).toBe(204); + + await registerCandidate(page, "support-reader"); + await page.goto(casePath); + const foreignDetail = page.waitForResponse( + (response) => + new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` && + response.request().method() === "GET", + ); + await page.reload(); + expect((await foreignDetail).status()).toBe(404); + await expect(page.getByText("Обращение не найдено или недоступно")).toBeVisible(); + await expect(page.getByText(description, { exact: true })).toHaveCount(0); + }); + + test("allows a manual request after C3 revocation without an attempt or an automatic grant", async ({ + page, + }) => { + await registerCandidate(page, "manual-author"); + await page.goto("/candidate/privacy"); + await expect( + page.getByRole("heading", { name: "Согласия и настройки приватности" }), + ).toBeVisible(); + + const c3Text = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consent-texts/c3" && + response.request().method() === "GET", + ); + await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); + expect((await c3Text).status()).toBe(200); + await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); + const grantList = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents" && + response.request().method() === "GET", + ); + const grantResponse = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents/c3" && + response.request().method() === "PUT", + ); + await page.getByRole("button", { name: "Дать согласие C3" }).click(); + expect((await grantResponse).status()).toBe(200); + const activeC3List = (await (await grantList).json()) as ConsentList; + expect( + activeC3List.items.some((record) => record.purpose === "c3" && record.state === "active"), + ).toBe(true); + + await page.getByRole("button", { name: "Отозвать C3", exact: true }).click(); + await page.getByLabel("Я понимаю последствия отзыва C3.").check(); + const revokeList = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents" && + response.request().method() === "GET", + ); + const revokeResponse = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents/c3" && + response.request().method() === "DELETE", + ); + await page.getByRole("button", { name: "Подтвердить отзыв" }).click(); + expect((await revokeResponse).status()).toBe(204); + const revokedC3List = (await (await revokeList).json()) as ConsentList; + expect( + revokedC3List.items.some((record) => record.purpose === "c3" && record.state === "active"), + ).toBe(false); + + const attemptRequests: string[] = []; + page.on("request", (request) => { + const url = new URL(request.url()); + if (url.pathname === "/api/v1/me/assessment-attempts") attemptRequests.push(request.method()); + }); + await page.goto("/candidate/support/cases/manual-assessment"); + const specialization = page.getByLabel("Специальность"); + await expect(specialization.locator("option[value='frontend']")).toHaveCount(1); + await specialization.selectOption("frontend"); + await expect(page.getByText(/Запрос ручной оценки остается доступен/)).toBeVisible(); + await page.getByLabel("Желаемый грейд").selectOption("junior"); + const reason = "Прошу эксперта оценить эту категорию вручную."; + const description = page.getByLabel("Почему вы просите ручную оценку"); + await description.fill(reason); + await expect(page.getByText(/не требует C3/)).toBeVisible(); + await checkResponsiveForm(page, specialization); + + await page.setViewportSize({ width: 360, height: 900 }); + const submitButton = page.getByRole("button", { name: "Отправить запрос эксперту" }); + await focusByKeyboard(page, submitButton); + const createResponsePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/support-cases" && + response.request().method() === "POST", + ); + await page.keyboard.press("Enter"); + const createResponse = await createResponsePromise; + expect(createResponse.status()).toBe(201); + const createBody = createResponse.request().postDataJSON() as Record; + expect(createBody).toMatchObject({ + type: "manual_assessment", + description: reason, + assessment_target: { specialization: "frontend", grade: "junior" }, + }); + expect("object" in createBody).toBe(false); + const created = (await createResponse.json()) as SupportCaseResponse; + expect(created.type).toBe("manual_assessment"); + expect(created.status).toBe("waiting_expert"); + expect(created.assessment_target).toEqual({ specialization: "frontend", grade: "junior" }); + expect(created.rubric_version).toBeNull(); + expect(created.decision).toBeNull(); + expect(attemptRequests).toEqual([]); + await expect( + page.getByText( + "Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась.", + ), + ).toBeVisible(); + + const detailResponsePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` && + response.request().method() === "GET", + ); + await page.reload(); + expect((await detailResponsePromise).status()).toBe(200); + await expect(page.getByText(reason, { exact: true })).toBeVisible(); + const replayed = await replaySupportCaseCreate(page, createResponse); + expect(replayed.id).toBe(created.id); + const supportList = await page.evaluate(async () => { + const response = await fetch("/api/v1/me/support-cases?limit=100", { + credentials: "include", + }); + if (!response.ok) throw new Error("Could not read the local support case list."); + return (await response.json()) as SupportCaseListResponse; + }); + expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1); + + const activeC3AfterRequest = await page.evaluate(async () => { + const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" }); + if (!response.ok) return null; + const body = (await response.json()) as ConsentList; + return body.items.some((record) => record.purpose === "c3" && record.state === "active"); + }); + expect(activeC3AfterRequest).toBe(false); + + await page.goto("/candidate/support/cases/manual-assessment"); + await page.getByLabel("Специальность").selectOption("backend"); + await page.getByLabel("Желаемый грейд").selectOption("junior"); + const backendReason = "Прошу эксперта оценить Backend на уровне Junior."; + await page.getByLabel("Почему вы просите ручную оценку").fill(backendReason); + const backendCreatePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/support-cases" && + response.request().method() === "POST", + ); + await page.getByRole("button", { name: "Отправить запрос эксперту" }).click(); + const backendCreateResponse = await backendCreatePromise; + expect(backendCreateResponse.status()).toBe(201); + expect(backendCreateResponse.request().postDataJSON()).toMatchObject({ + type: "manual_assessment", + description: backendReason, + assessment_target: { specialization: "backend", grade: "junior" }, + }); + const backendCase = (await backendCreateResponse.json()) as SupportCaseResponse; + expect(backendCase.type).toBe("manual_assessment"); + expect(backendCase.status).toBe("waiting_expert"); + expect(backendCase.assessment_target).toEqual({ specialization: "backend", grade: "junior" }); + expect(backendCase.rubric_version).toEqual(expect.any(Number)); + expect(backendCase.rubric_version).toBeGreaterThan(0); + expect(backendCase.decision).toBeNull(); + expect(attemptRequests).toEqual([]); + + const activeC3AfterPublishedManualRequest = await page.evaluate(async () => { + const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" }); + if (!response.ok) return null; + const body = (await response.json()) as ConsentList; + return body.items.some((record) => record.purpose === "c3" && record.state === "active"); + }); + expect(activeC3AfterPublishedManualRequest).toBe(false); + }); +}); diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 7ad208e..a48e3c9 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -21,6 +21,8 @@ export default defineConfig({ testDir: "./e2e", outputDir: `${artifactsDir}/results`, forbidOnly: Boolean(process.env.CI), + // The browser container has two CPUs; host-based defaults oversubscribe it. + workers: 2, retries: 0, reporter: [["list"], ["html", { outputFolder: `${artifactsDir}/report`, open: "never" }]], use: { diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index e537ddb..5ecae16 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -2,8 +2,10 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { renderToString } from "react-dom/server"; import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom"; import { describe, expect, it } from "vitest"; +import { assessmentQueryKeys } from "../../entities/assessment"; import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent"; import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../shared/api/schemas"; import { createQueryClient } from "../providers/query-client"; import { routes } from "./routes"; @@ -20,7 +22,7 @@ async function render(path: string): Promise { const queryClient = createQueryClient(); const scenario = path.startsWith("/employer") ? "employer" : "candidate"; if (path.startsWith("/candidate") || path.startsWith("/employer")) { - queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + const session = { account: { id: "11111111-1111-4111-8111-111111111111", email: "person@example.test", @@ -39,7 +41,17 @@ async function render(path: string): Promise { created_at: "2026-10-07T12:00:00Z", }, csrf_token: "A".repeat(43), - }); + } satisfies Session; + queryClient.setQueryData(getGetCurrentSessionQueryKey(), session); + if (path === "/candidate/assessment") { + queryClient.setQueryData(assessmentQueryKeys.availability(session), { specializations: [] }); + queryClient.setQueryData(assessmentQueryKeys.questionnaire(session), { + version: 0, + specializations: [], + work_context: null, + updated_at: null, + }); + } } if (path.startsWith("/candidate/privacy")) { const hasMore = path.includes("history=partial"); @@ -122,7 +134,23 @@ describe("route groups", () => { ["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"], ["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"], ["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"], + ["/candidate/assessment", "Проверка знаний", "Разделы кабинета кандидата"], + [ + "/candidate/assessment/01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80", + "Попытка проверки", + "Разделы кабинета кандидата", + ], ["/employer/company", "Компания", "Разделы кабинета работодателя"], + ["/employer/needs", "Потребности", "Разделы кабинета работодателя"], + ["/candidate/support/cases", "Мои обращения", "Разделы кабинета кандидата"], + ["/candidate/support/cases/new", "Обратиться в поддержку", "Разделы кабинета кандидата"], + [ + "/candidate/support/cases/manual-assessment", + "Запросить ручную оценку", + "Разделы кабинета кандидата", + ], + ["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"], + ["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"], ["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"], ])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => { const html = await renderHtml(path); @@ -183,6 +211,14 @@ describe("route groups", () => { }); describe("product readiness", () => { + it("keeps the training run available when no full-assessment category exists", async () => { + const html = await renderHtml("/candidate/assessment"); + + expect(html).toContain("Сначала выберите специализацию"); + expect(html).toContain("Начать демонстрацию"); + expect(html).not.toContain("Начать полную проверку"); + }); + it("presents the root page as a scaffold, not as a working product", async () => { const html = await renderHtml("/"); @@ -226,7 +262,7 @@ describe("product readiness", () => { }); it("labels the remaining cabinet scaffolds as placeholders", async () => { - for (const path of ["/candidate", "/employer/needs"]) { + for (const path of ["/candidate", "/employer/candidates"]) { expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач"); } }); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 2307839..165fe05 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -1,14 +1,23 @@ import { redirect, type RouteObject } from "react-router-dom"; +import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment"; import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; import { CompanyPage } from "../../pages/company"; import { ConsentsPage } from "../../pages/consents"; import { SessionGate } from "../../entities/session"; import { NotFoundPage } from "../../pages/not-found"; +import { NeedEditorPage } from "../../pages/need-editor"; +import { NeedListPage } from "../../pages/needs"; import { PlaceholderPage } from "../../pages/placeholder"; import { ProfilePage } from "../../pages/profile"; import { QuestionnairePage } from "../../pages/questionnaire"; import { StatusPage } from "../../pages/status"; +import { + CreateSupportCasePage, + ManualAssessmentPage, + SupportCaseDetailPage, + SupportCasesPage, +} from "../../pages/support-cases"; import { WelcomePage } from "../../pages/welcome"; import { paths } from "../../shared/config"; import { CandidateShell } from "../../widgets/candidate-shell"; @@ -17,6 +26,7 @@ import { PublicShell } from "../../widgets/public-shell"; import { RootLayout } from "../ui/root-layout"; import { RouteErrorPage } from "../ui/route-error-page"; import { CandidateHomeRoute } from "./candidate-home-route"; +import { SupportRoute } from "./support-route"; /** * Route tree with public pages and role-specific cabinets. Protected shells @@ -34,7 +44,7 @@ export const routes: RouteObject[] = [ { path: paths.login, element: }, { path: paths.register, element: }, { path: paths.verifyEmail, element: }, - { path: paths.support, element: }, + { path: paths.support, element: }, { path: paths.status, element: }, { path: "*", element: }, ], @@ -58,7 +68,11 @@ export const routes: RouteObject[] = [ }, { path: paths.candidate.assessment, - element: , + element: , + }, + { + path: `${paths.candidate.assessment}/:attemptId`, + element: , }, { path: paths.candidate.results, @@ -72,6 +86,13 @@ export const routes: RouteObject[] = [ path: paths.candidate.privacy, element: , }, + { path: paths.candidate.supportCases, element: }, + { path: paths.candidate.supportNew, element: }, + { path: paths.candidate.supportManual, element: }, + { + path: `${paths.candidate.supportCases}/:caseId`, + element: , + }, { path: "*", element: ( @@ -94,7 +115,15 @@ export const routes: RouteObject[] = [ path: paths.employer.company, element: , }, - { path: paths.employer.needs, element: }, + { path: paths.employer.needs, element: }, + { path: `${paths.employer.needs}/new`, element: }, + { path: `${paths.employer.needs}/:needId`, element: }, + { path: paths.employer.supportCases, element: }, + { path: paths.employer.supportNew, element: }, + { + path: `${paths.employer.supportCases}/:caseId`, + element: , + }, { path: paths.employer.candidates, element: , diff --git a/frontend/src/app/router/support-route.tsx b/frontend/src/app/router/support-route.tsx new file mode 100644 index 0000000..5901c51 --- /dev/null +++ b/frontend/src/app/router/support-route.tsx @@ -0,0 +1,57 @@ +import { Navigate, useLocation } from "react-router-dom"; +import { parseSupportCaseContext } from "../../entities/support-case"; +import { ApiRequestError } from "../../shared/api"; +import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity"; +import { paths } from "../../shared/config"; +import { ButtonLink, ErrorState, LoadingState, Page, Section } from "../../shared/ui"; + +/** Support remains reachable before completing either onboarding flow. */ +export function SupportRoute() { + const session = useGetCurrentSession(); + const location = useLocation(); + if (session.isPending) { + return ( + + + + ); + } + + if (session.isError) { + if (session.error instanceof ApiRequestError && session.error.status === 401) { + return ( + +
+ + Войти и открыть поддержку + +
+
+ ); + } + return ( + + void session.refetch()} + /> + + ); + } + + const state: unknown = location.state; + const context = + state && typeof state === "object" && !Array.isArray(state) + ? parseSupportCaseContext((state as Record).supportContext) + : null; + const cabinet = session.data.account.scenario === "candidate" ? paths.candidate : paths.employer; + return ( + + ); +} diff --git a/frontend/src/app/ui/route-error-page.tsx b/frontend/src/app/ui/route-error-page.tsx index 98d6243..f083b17 100644 --- a/frontend/src/app/ui/route-error-page.tsx +++ b/frontend/src/app/ui/route-error-page.tsx @@ -1,5 +1,6 @@ import { useRouteError } from "react-router-dom"; -import { ErrorState, Page } from "../../shared/ui"; +import { paths } from "../../shared/config"; +import { ErrorState, Page, TextLink } from "../../shared/ui"; /** * Last-resort boundary for errors thrown while rendering a route. It has no @@ -18,6 +19,7 @@ export function RouteErrorPage() { window.location.reload(); }} /> + Обратиться в поддержку ); diff --git a/frontend/src/entities/assessment/api/assessment-queries.ts b/frontend/src/entities/assessment/api/assessment-queries.ts new file mode 100644 index 0000000..44b965c --- /dev/null +++ b/frontend/src/entities/assessment/api/assessment-queries.ts @@ -0,0 +1,122 @@ +import { useQuery, type QueryClient } from "@tanstack/react-query"; +import { + getMyAssessmentAvailability, + getMyAssessmentAttempt, + getMyAssessmentResult, +} from "../../../shared/api/endpoints/assessment/assessment"; +import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate"; +import type { + AssessmentAttempt, + AssessmentAvailability, + AssessmentResult, + Session, +} from "../../../shared/api/schemas"; +import { + parseAssessmentAvailabilityResponse, + parseAssessmentAttemptResponse, + parseAssessmentResultResponse, + parseCandidateQuestionnaireResponse, +} from "../model/contract-validation"; +import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session"; + +type AssessmentQueryOptions = { + enabled?: boolean; + queryClient: QueryClient; + actor: Session | undefined; +}; + +const privateQueryOptions = { + gcTime: 0, + staleTime: 0, + refetchOnMount: "always" as const, + refetchOnWindowFocus: "always" as const, + retry: false, +}; + +export function useAssessmentAvailability({ + actor, + enabled = true, + queryClient, +}: AssessmentQueryOptions) { + return useQuery({ + queryKey: actor + ? assessmentQueryKeys.availability(actor) + : [...assessmentQueryKeysPrefix, "availability"], + enabled: Boolean(actor && enabled), + ...privateQueryOptions, + queryFn: async ({ signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const availability = await getMyAssessmentAvailability({ signal }); + assertCurrentAssessmentSession(queryClient, actor); + return parseAssessmentAvailabilityResponse(availability); + }, + }); +} + +export function useAssessmentQuestionnaire({ + actor, + enabled = true, + queryClient, +}: AssessmentQueryOptions) { + return useQuery({ + queryKey: actor + ? assessmentQueryKeys.questionnaire(actor) + : [...assessmentQueryKeysPrefix, "questionnaire"], + enabled: Boolean(actor && enabled), + ...privateQueryOptions, + queryFn: async ({ signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const questionnaire = await getMyQuestionnaire({ signal }); + assertCurrentAssessmentSession(queryClient, actor); + return parseCandidateQuestionnaireResponse(questionnaire); + }, + }); +} + +export function useAssessmentAttempt({ + actor, + attemptId, + enabled = true, + queryClient, +}: AssessmentQueryOptions & { attemptId: string }) { + return useQuery({ + queryKey: actor + ? assessmentQueryKeys.attempt(actor, attemptId) + : [...assessmentQueryKeysPrefix, "attempt", attemptId], + enabled: Boolean(actor && attemptId && enabled), + ...privateQueryOptions, + refetchInterval: (query) => { + const attempt = query.state.data; + return attempt?.practices.some((practice) => practice.status === "pending") ? 2500 : false; + }, + queryFn: async ({ signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const response = await getMyAssessmentAttempt(attemptId, { signal }); + assertCurrentAssessmentSession(queryClient, actor); + return parseAssessmentAttemptResponse(response); + }, + }); +} + +export function useAssessmentResult({ + actor, + attemptId, + enabled = true, + queryClient, +}: AssessmentQueryOptions & { attemptId: string }) { + return useQuery({ + queryKey: actor + ? assessmentQueryKeys.result(actor, attemptId) + : [...assessmentQueryKeysPrefix, "result", attemptId], + enabled: Boolean(actor && attemptId && enabled), + ...privateQueryOptions, + queryFn: async ({ signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const response = await getMyAssessmentResult(attemptId, { signal }); + assertCurrentAssessmentSession(queryClient, actor); + return parseAssessmentResultResponse(response); + }, + }); +} + +const assessmentQueryKeysPrefix = ["candidate-assessment"] as const; diff --git a/frontend/src/entities/assessment/index.ts b/frontend/src/entities/assessment/index.ts new file mode 100644 index 0000000..55153cb --- /dev/null +++ b/frontend/src/entities/assessment/index.ts @@ -0,0 +1,29 @@ +export { + useAssessmentAttempt, + useAssessmentAvailability, + useAssessmentQuestionnaire, + useAssessmentResult, +} from "./api/assessment-queries"; +export { + assessmentQueryKeys, + assessmentQueryPrefix, + assessmentSessionMatches, + assertCurrentAssessmentSession, + isCurrentAssessmentSession, + removeAssessmentQueries, + removeAssessmentQueriesForSessionChange, +} from "./model/session"; +export { isOutcomeAmbiguous } from "./model/idempotency"; +export { + parseAssessmentAttemptResponse, + parseAssessmentResultResponse, +} from "./model/contract-validation"; +export { assessmentResultSummary } from "./model/result-summary"; +export { + availabilityLabels, + gradeLabels, + methodLabel, + outcomeLabels, + selectedSpecialization, + specializationLabels, +} from "./model/labels"; diff --git a/frontend/src/entities/assessment/model/contract-validation.test.ts b/frontend/src/entities/assessment/model/contract-validation.test.ts new file mode 100644 index 0000000..a31ceca --- /dev/null +++ b/frontend/src/entities/assessment/model/contract-validation.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import type { AssessmentAttempt } from "../../../shared/api/schemas"; +import { + parseAssessmentAvailabilityResponse, + parseAssessmentAttemptResponse, + parseAssessmentResultResponse, + parseCandidateQuestionnaireResponse, +} from "./contract-validation"; + +const validAttempt: AssessmentAttempt = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01", + version: 2, + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "python", + root_attempt_id: null, + chain_deadline: null, + mode: "demo_basic", + state: "in_progress", + versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" }, + started_at: "2026-10-08T10:00:00Z", + expires_at: "2026-10-08T11:00:00Z", + sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, + finished_at: null, + progress: { answered_items: 1, max_items: 2 }, + current_item: { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02", + sequence: 2, + prompt: "Сколько?", + content: { format: "number", unit: null }, + }, + practices: [], +}; + +function captureError(operation: () => unknown): unknown { + try { + operation(); + } catch (error: unknown) { + return error; + } + return undefined; +} + +describe("assessment response contract validation", () => { + it("accepts an empty availability and an unsaved questionnaire", () => { + expect(parseAssessmentAvailabilityResponse({ specializations: [] })).toEqual({ + specializations: [], + }); + expect( + parseCandidateQuestionnaireResponse({ + version: 0, + specializations: [], + work_context: null, + updated_at: null, + }), + ).toEqual({ + version: 0, + specializations: [], + work_context: null, + updated_at: null, + }); + }); + + it.each([ + ["availability", parseAssessmentAvailabilityResponse], + ["questionnaire", parseCandidateQuestionnaireResponse], + ] as const)("rejects an invalid %s response", (_name, parse) => { + const error = captureError(() => parse({})); + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ status: 200, code: invalidResponseCode }); + }); + + it("accepts a complete attempt payload", () => { + expect(parseAssessmentAttemptResponse(validAttempt)).toEqual(validAttempt); + }); + + it.each([{}, { id: validAttempt.id, version: validAttempt.version }])( + "rejects an incomplete successful attempt payload", + (value) => { + const error = captureError(() => parseAssessmentAttemptResponse(value, 201)); + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ status: 201, code: invalidResponseCode }); + }, + ); + + it("rejects an incomplete successful result payload", () => { + expect(() => parseAssessmentResultResponse({})).toThrowError( + expect.objectContaining({ status: 200, code: invalidResponseCode }), + ); + }); +}); diff --git a/frontend/src/entities/assessment/model/contract-validation.ts b/frontend/src/entities/assessment/model/contract-validation.ts new file mode 100644 index 0000000..68b0ff6 --- /dev/null +++ b/frontend/src/entities/assessment/model/contract-validation.ts @@ -0,0 +1,49 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { + AssessmentAttempt as assessmentAttemptSchema, + AssessmentAvailability as assessmentAvailabilitySchema, + AssessmentResult as assessmentResultSchema, + CandidateQuestionnaire as candidateQuestionnaireSchema, + type AssessmentAttempt, + type AssessmentAvailability, + type AssessmentResult, + type CandidateQuestionnaire, +} from "../../../shared/api/schemas"; + +function invalidAssessmentResponse(status: number): ApiRequestError { + return new ApiRequestError({ + status, + code: invalidResponseCode, + title: "The response does not match the API contract.", + }); +} + +export function parseAssessmentAttemptResponse(value: unknown, status = 200): AssessmentAttempt { + const parsed = assessmentAttemptSchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} + +export function parseAssessmentAvailabilityResponse( + value: unknown, + status = 200, +): AssessmentAvailability { + const parsed = assessmentAvailabilitySchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} + +export function parseCandidateQuestionnaireResponse( + value: unknown, + status = 200, +): CandidateQuestionnaire { + const parsed = candidateQuestionnaireSchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} + +export function parseAssessmentResultResponse(value: unknown, status = 200): AssessmentResult { + const parsed = assessmentResultSchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} diff --git a/frontend/src/entities/assessment/model/idempotency.test.ts b/frontend/src/entities/assessment/model/idempotency.test.ts new file mode 100644 index 0000000..68a2c73 --- /dev/null +++ b/frontend/src/entities/assessment/model/idempotency.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { + ApiRequestError, + invalidResponseCode, + networkErrorCode, + type ApiErrorCode, +} from "../../../shared/api"; +import { isOutcomeAmbiguous } from "./idempotency"; + +const ambiguousOutcomes: ReadonlyArray = [ + [0, networkErrorCode], + [200, invalidResponseCode], + [429, "rate_limited"], + [500, "internal"], +]; + +describe("assessment command retry safety", () => { + it.each(ambiguousOutcomes)( + "keeps the idempotency key when outcome status is %s", + (status, code) => { + expect( + isOutcomeAmbiguous(new ApiRequestError({ status, code, title: "Request failed." })), + ).toBe(true); + }, + ); + + it.each([400, 401, 403, 404, 409, 412, 422])( + "does not classify deterministic HTTP %s as an ambiguous outcome", + (status) => { + expect( + isOutcomeAmbiguous( + new ApiRequestError({ status, code: "validation_failed", title: "Rejected." }), + ), + ).toBe(false); + }, + ); + + it("does not treat local validation errors as a request outcome", () => { + expect(isOutcomeAmbiguous(new Error("Invalid form state."))).toBe(false); + }); +}); diff --git a/frontend/src/entities/assessment/model/idempotency.ts b/frontend/src/entities/assessment/model/idempotency.ts new file mode 100644 index 0000000..9c7bc6e --- /dev/null +++ b/frontend/src/entities/assessment/model/idempotency.ts @@ -0,0 +1,11 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; + +export function isOutcomeAmbiguous(error: unknown): boolean { + return ( + error instanceof ApiRequestError && + (error.status === 0 || + error.status >= 500 || + error.status === 429 || + error.code === invalidResponseCode) + ); +} diff --git a/frontend/src/entities/assessment/model/labels.ts b/frontend/src/entities/assessment/model/labels.ts new file mode 100644 index 0000000..1b98934 --- /dev/null +++ b/frontend/src/entities/assessment/model/labels.ts @@ -0,0 +1,59 @@ +import type { + AssessmentAvailability, + AssessmentGradeAvailabilityStatus, + AssessmentMode, + AssessmentOutcome, + AssessmentSpecializationAvailability, + GradeCode, + SpecializationCode, +} from "../../../shared/api/schemas"; + +export const specializationLabels: Readonly> = { + backend: "Backend", + frontend: "Frontend", + mobile: "Мобильная разработка", + network_engineer: "Сетевые технологии", + devops_sre: "DevOps и SRE", + data_analyst: "Аналитика данных", + ds_ml: "Data Science и ML", + information_security: "Информационная безопасность", + qa: "Тестирование", +}; + +export const gradeLabels: Readonly> = { + intern: "Стажер", + junior: "Junior", + middle: "Middle", + senior: "Senior", +}; + +export const availabilityLabels: Readonly> = { + available: "Можно начать", + active_attempt: "Есть незавершенная попытка", + cooldown: "Пока недоступно", + insufficient_bank: "Проверка еще не подготовлена", +}; + +export const outcomeLabels: Readonly> = { + confirmed: "Уровень подтвержден", + not_confirmed: "Уровень пока не подтвержден", + not_determined: "Результат не определен", +}; + +export function methodLabel(mode: AssessmentMode): string { + switch (mode) { + case "adaptive": + return "Адаптивная проверка"; + case "demo_basic": + return "Базовая проверка по фиксированному набору заданий"; + case "demo_express": + return "Демонстрационный экспресс-запуск"; + } +} + +export function selectedSpecialization( + availability: AssessmentAvailability, + code: SpecializationCode | undefined, +): AssessmentSpecializationAvailability | undefined { + return availability.specializations.find((item) => item.specialization === code); +} diff --git a/frontend/src/entities/assessment/model/session.ts b/frontend/src/entities/assessment/model/session.ts new file mode 100644 index 0000000..31b0ad7 --- /dev/null +++ b/frontend/src/entities/assessment/model/session.ts @@ -0,0 +1,65 @@ +import type { QueryClient, QueryKey, QueryState } from "@tanstack/react-query"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; + +type SessionSnapshot = Pick, "data" | "status">; + +export function assessmentSessionMatches( + snapshot: SessionSnapshot | undefined, + actor: Session | undefined, +): boolean { + return Boolean( + snapshot?.status === "success" && + actor && + snapshot.data?.account.id === actor.account.id && + snapshot.data.csrf_token === actor.csrf_token && + actor.account.scenario === "candidate", + ); +} + +export function isCurrentAssessmentSession( + queryClient: QueryClient, + actor: Session | undefined, +): boolean { + return assessmentSessionMatches( + queryClient.getQueryState(getGetCurrentSessionQueryKey()), + actor, + ); +} + +export function assertCurrentAssessmentSession( + queryClient: QueryClient, + actor: Session | undefined, +): asserts actor is Session { + if (!isCurrentAssessmentSession(queryClient, actor)) { + throw new Error("The candidate session changed during the assessment request."); + } +} + +export const assessmentQueryPrefix = ["candidate-assessment"] as const; + +export const assessmentQueryKeys = { + availability: (actor: Session) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "availability"] as const, + questionnaire: (actor: Session) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "questionnaire"] as const, + attempt: (actor: Session, attemptId: string) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "attempt", attemptId] as const, + result: (actor: Session, attemptId: string) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result", attemptId] as const, +}; + +export function removeAssessmentQueries(queryClient: QueryClient): void { + queryClient.removeQueries({ queryKey: assessmentQueryPrefix }); +} + +export function removeAssessmentQueriesForSessionChange( + queryClient: QueryClient, + previousKey?: QueryKey, +): void { + if (previousKey) { + queryClient.removeQueries({ queryKey: previousKey }); + return; + } + removeAssessmentQueries(queryClient); +} diff --git a/frontend/src/entities/need/api/cache.test.ts b/frontend/src/entities/need/api/cache.test.ts new file mode 100644 index 0000000..e321bdd --- /dev/null +++ b/frontend/src/entities/need/api/cache.test.ts @@ -0,0 +1,64 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization"; +import { needQueryKeys } from "../model/query-keys"; +import { + removeAllNeedQueries, + removeNeedQueriesForOrganization, + removeNeedQueriesForSessionChange, +} from "./cache"; + +const accountId = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4"; +const organizationId = "f4866808-70dc-4cbe-b98e-05009c8171d4"; +const otherOrganizationId = "e0102126-0c16-49f8-8e81-a82949710454"; +const needId = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91"; + +describe("need query cache cleanup", () => { + it("removes every list and detail for a denied organization only", () => { + const client = new QueryClient(); + const deniedListKey = needQueryKeys.list(accountId, organizationId); + const deniedDetailKey = needQueryKeys.detail(accountId, organizationId, needId); + const otherListKey = needQueryKeys.list(accountId, otherOrganizationId); + + client.setQueryData(deniedListKey, { items: [] }); + client.setQueryData(deniedDetailKey, { id: needId }); + client.setQueryData(otherListKey, { items: [] }); + + removeNeedQueriesForOrganization(client, organizationId); + + expect(client.getQueryData(deniedListKey)).toBeUndefined(); + expect(client.getQueryData(deniedDetailKey)).toBeUndefined(); + expect(client.getQueryData(otherListKey)).toEqual({ items: [] }); + }); + + it("clears need and owner-directory caches when the session changes", () => { + const client = new QueryClient(); + const directoryKey = getListMyOrganizationsQueryKey({ limit: 100 }); + const listKey = needQueryKeys.list(accountId, organizationId); + const detailKey = needQueryKeys.detail(accountId, organizationId, needId); + + client.setQueryData(directoryKey, { items: [] }); + client.setQueryData(listKey, { items: [] }); + client.setQueryData(detailKey, { id: needId }); + + removeNeedQueriesForSessionChange(client); + + expect(client.getQueryData(directoryKey)).toBeUndefined(); + expect(client.getQueryData(listKey)).toBeUndefined(); + expect(client.getQueryData(detailKey)).toBeUndefined(); + }); + + it("clears private need data if the owner directory loses authorization", () => { + const client = new QueryClient(); + const firstNeedKey = needQueryKeys.list(accountId, organizationId); + const secondNeedKey = needQueryKeys.detail(accountId, otherOrganizationId, needId); + + client.setQueryData(firstNeedKey, { items: [] }); + client.setQueryData(secondNeedKey, { id: needId }); + + removeAllNeedQueries(client); + + expect(client.getQueryData(firstNeedKey)).toBeUndefined(); + expect(client.getQueryData(secondNeedKey)).toBeUndefined(); + }); +}); diff --git a/frontend/src/entities/need/api/cache.ts b/frontend/src/entities/need/api/cache.ts new file mode 100644 index 0000000..41d8fd6 --- /dev/null +++ b/frontend/src/entities/need/api/cache.ts @@ -0,0 +1,40 @@ +import type { QueryClient } from "@tanstack/react-query"; + +/** Removes every private need list/detail cache for one organization. */ +export function removeNeedQueriesForOrganization( + queryClient: QueryClient, + organizationId: string, +): void { + const prefix = `/api/v1/organizations/${organizationId}/needs`; + void queryClient.removeQueries({ + predicate: (query) => { + const key = query.queryKey[0]; + return typeof key === "string" && (key === prefix || key.startsWith(`${prefix}/`)); + }, + }); +} + +/** Removes every private need query when the owner directory cannot be trusted. */ +export function removeAllNeedQueries(queryClient: QueryClient): void { + void queryClient.removeQueries({ + predicate: (query) => { + const key = query.queryKey[0]; + return ( + typeof key === "string" && + key.startsWith("/api/v1/organizations/") && + key.includes("/needs") + ); + }, + }); +} + +/** Clears need and owner-directory caches when a session identity changes. */ +export function removeNeedQueriesForSessionChange(queryClient: QueryClient): void { + void queryClient.removeQueries({ + predicate: (query) => { + const key = query.queryKey[0]; + return typeof key === "string" && key === "/api/v1/me/organizations"; + }, + }); + removeAllNeedQueries(queryClient); +} diff --git a/frontend/src/entities/need/api/organization-directory.ts b/frontend/src/entities/need/api/organization-directory.ts new file mode 100644 index 0000000..eb236b4 --- /dev/null +++ b/frontend/src/entities/need/api/organization-directory.ts @@ -0,0 +1,37 @@ +import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; +import { listMyOrganizations } from "../../../shared/api/endpoints/organization/organization"; +import type { Session } from "../../../shared/api/schemas"; +import { needDirectoryPageSize, needQueryKeys } from "../model/query-keys"; +import { isNeedSessionCurrent } from "./session"; + +/** Reads the signed-in account's organization directory for need context checks. */ +export function useNeedOrganizationDirectory(session: Session | undefined, enabled: boolean) { + const queryClient = useQueryClient(); + const accountId = session?.account.id; + const scopedAccountId = accountId ?? "no-session"; + const csrfToken = session?.csrf_token; + + return useInfiniteQuery({ + queryKey: needQueryKeys.directory(scopedAccountId), + initialPageParam: undefined as string | undefined, + queryFn: async ({ pageParam, signal }) => { + if (!isNeedSessionCurrent(queryClient, session)) + throw new Error("The session changed before the directory request."); + const result = await listMyOrganizations( + { limit: needDirectoryPageSize, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal }, + ); + if (!isNeedSessionCurrent(queryClient, session)) + throw new Error("The session changed during the directory request."); + return result; + }, + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + enabled: enabled && accountId !== undefined && csrfToken !== undefined, + gcTime: 0, + staleTime: 0, + refetchOnMount: "always", + refetchOnWindowFocus: "always", + retry: false, + }); +} diff --git a/frontend/src/entities/need/api/session.test.ts b/frontend/src/entities/need/api/session.test.ts new file mode 100644 index 0000000..9253a75 --- /dev/null +++ b/frontend/src/entities/need/api/session.test.ts @@ -0,0 +1,34 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; +import { isNeedSessionCurrent } from "./session"; + +const session: Session = { + account: { + id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", + email: "owner@example.test", + email_verified: true, + scenario: "employer", + onboarding_step: "completed", + created_at: "2026-10-06T09:00:00Z", + }, + csrf_token: "abcdefghijklmnopqrstuvwxyz123456", +}; + +describe("isNeedSessionCurrent", () => { + it("matches both the account and current CSRF token", () => { + const client = new QueryClient(); + client.setQueryData(getGetCurrentSessionQueryKey(), session); + + expect(isNeedSessionCurrent(client, session)).toBe(true); + expect(isNeedSessionCurrent(client, { ...session, csrf_token: "another-token" })).toBe(false); + expect( + isNeedSessionCurrent(client, { + ...session, + account: { ...session.account, id: "36acbba3-d786-4c3a-95b2-4c374ab3206e" }, + }), + ).toBe(false); + expect(isNeedSessionCurrent(client, undefined)).toBe(false); + }); +}); diff --git a/frontend/src/entities/need/api/session.ts b/frontend/src/entities/need/api/session.ts new file mode 100644 index 0000000..392073a --- /dev/null +++ b/frontend/src/entities/need/api/session.ts @@ -0,0 +1,17 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; + +/** Checks that a response still belongs to the active account and CSRF session. */ +export function isNeedSessionCurrent( + queryClient: QueryClient, + session: Session | undefined, +): boolean { + if (!session?.csrf_token) return false; + const state = queryClient.getQueryState(getGetCurrentSessionQueryKey()); + return Boolean( + state?.status === "success" && + state.data?.account.id === session.account.id && + state.data.csrf_token === session.csrf_token, + ); +} diff --git a/frontend/src/entities/need/index.ts b/frontend/src/entities/need/index.ts index 143936c..903c2df 100644 --- a/frontend/src/entities/need/index.ts +++ b/frontend/src/entities/need/index.ts @@ -5,6 +5,13 @@ // toUpdateBody with the generated mutations. After a successful update the // returned Need is the new baseline of the draft. +export { useNeedOrganizationDirectory } from "./api/organization-directory"; +export { + removeAllNeedQueries, + removeNeedQueriesForOrganization, + removeNeedQueriesForSessionChange, +} from "./api/cache"; +export { isNeedSessionCurrent } from "./api/session"; export { addSkill, addTask, @@ -23,6 +30,9 @@ export { setFieldValue, } from "./model/edit"; export { fromTransport, NeedTransportError } from "./model/from-transport"; +export { rebaseNeedDraft } from "./model/rebase"; +export { activeNeedOrganizations, type NeedOrganization } from "./model/owner-organizations"; +export { needDirectoryPageSize, needListPageSize, needQueryKeys } from "./model/query-keys"; export { changedNeedFields, isNeedFormDirty, diff --git a/frontend/src/entities/need/model/need-form.test.ts b/frontend/src/entities/need/model/need-form.test.ts index e6a2f94..0fdef7e 100644 --- a/frontend/src/entities/need/model/need-form.test.ts +++ b/frontend/src/entities/need/model/need-form.test.ts @@ -29,6 +29,7 @@ import { setFieldValue, } from "./edit"; import { fromTransport, NeedTransportError } from "./from-transport"; +import { rebaseNeedDraft } from "./rebase"; import { changedNeedFields, isNeedFormDirty, @@ -410,6 +411,45 @@ describe("toUpdateBody", () => { }); }); +describe("rebaseNeedDraft", () => { + it("keeps local edits and adopts untouched fields from the latest version", () => { + const baseline = fromTransport(extractedNeed); + let draft = setFieldValue(baseline, "grade", "middle"); + draft = removeSkill(draft, "requiredSkills", skillIndex(draft, "requiredSkills", "PostgreSQL")); + const latest = Need.parse({ + ...extractedNeed, + version: 2, + title: "Backend for the payments team, updated", + requirements: { + ...extractedNeed.requirements, + domain: { + status: "confirmed", + value: "payments", + source: { + origin: "manual", + quote: null, + extracted_in_version: null, + extraction_version: null, + }, + }, + }, + }); + + const rebased = rebaseNeedDraft(extractedNeed, draft, latest); + const body = toUpdateBody(latest, rebased); + + expect(rebased.title).toBe(latest.title); + expect(rebased.domain).toMatchObject({ status: "confirmed", value: "payments" }); + expect(rebased.grade).toEqual({ status: "confirmed", value: "middle", source: null }); + expect(rebased.requiredSkills.map((skill) => skill.name)).not.toContain("PostgreSQL"); + expect(body.expected_version).toBe(2); + expect(body.title).toBeUndefined(); + expect(body.domain).toBeUndefined(); + expect(body.grade).toEqual({ value: "middle", status: "confirmed" }); + expect(body.required_skills?.map((skill) => skill.name)).not.toContain("PostgreSQL"); + }); +}); + describe("toCreateBody", () => { function manualDraft(): NeedFormValues { let form: NeedFormValues = { ...emptyNeedForm(), title: createManual.title }; diff --git a/frontend/src/entities/need/model/owner-organizations.test.ts b/frontend/src/entities/need/model/owner-organizations.test.ts new file mode 100644 index 0000000..2d2910b --- /dev/null +++ b/frontend/src/entities/need/model/owner-organizations.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import type { MyOrganizationList } from "../../../shared/api/schemas"; +import { activeNeedOrganizations } from "./owner-organizations"; + +function organization(role: "owner" | "recruiter", state: "active" | "removed", id: string) { + return { + organization: { id, name: `Company ${id}`, verification_level: "e0" }, + membership: { + organization_id: id, + role, + state, + joined_at: "2026-09-01T00:00:00Z", + }, + } satisfies MyOrganizationList["items"][number]; +} + +describe("activeNeedOrganizations", () => { + it("keeps only active owner memberships across loaded pages", () => { + const pages: MyOrganizationList[] = [ + { + items: [ + organization("owner", "active", "00000000-0000-4000-8000-000000000001"), + organization("recruiter", "active", "00000000-0000-4000-8000-000000000002"), + ], + page: { has_more: true, next_cursor: "next" }, + }, + { + items: [organization("owner", "removed", "00000000-0000-4000-8000-000000000003")], + page: { has_more: false, next_cursor: null }, + }, + ]; + + expect(activeNeedOrganizations(pages).map((item) => item.organization.id)).toEqual([ + "00000000-0000-4000-8000-000000000001", + ]); + }); +}); diff --git a/frontend/src/entities/need/model/owner-organizations.ts b/frontend/src/entities/need/model/owner-organizations.ts new file mode 100644 index 0000000..988b23b --- /dev/null +++ b/frontend/src/entities/need/model/owner-organizations.ts @@ -0,0 +1,12 @@ +import type { MyOrganizationList } from "../../../shared/api/schemas"; + +export type NeedOrganization = MyOrganizationList["items"][number]; + +/** Returns only active owner contexts; other active roles grant no need access. */ +export function activeNeedOrganizations(pages: readonly MyOrganizationList[]): NeedOrganization[] { + return pages.flatMap((page) => + page.items.filter( + (item) => item.membership.role === "owner" && item.membership.state === "active", + ), + ); +} diff --git a/frontend/src/entities/need/model/query-keys.test.ts b/frontend/src/entities/need/model/query-keys.test.ts new file mode 100644 index 0000000..4c34a20 --- /dev/null +++ b/frontend/src/entities/need/model/query-keys.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { needQueryKeys } from "./query-keys"; + +const firstAccount = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4"; +const secondAccount = "36acbba3-d786-4c3a-95b2-4c374ab3206e"; +const firstOrganization = "f4866808-70dc-4cbe-b98e-05009c8171d4"; +const secondOrganization = "e0102126-0c16-49f8-8e81-a82949710454"; +const firstNeed = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91"; +const secondNeed = "ae85244a-a0c9-432d-a863-c99f63bb2677"; + +describe("need query keys", () => { + it("separates directory and need data by the active account", () => { + expect(needQueryKeys.directory(firstAccount)).not.toEqual( + needQueryKeys.directory(secondAccount), + ); + expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual( + needQueryKeys.list(secondAccount, firstOrganization), + ); + }); + + it("separates organization list and need detail contexts", () => { + expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual( + needQueryKeys.list(firstAccount, secondOrganization), + ); + expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual( + needQueryKeys.detail(firstAccount, firstOrganization, secondNeed), + ); + expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual( + needQueryKeys.detail(firstAccount, secondOrganization, firstNeed), + ); + }); +}); diff --git a/frontend/src/entities/need/model/query-keys.ts b/frontend/src/entities/need/model/query-keys.ts new file mode 100644 index 0000000..3931566 --- /dev/null +++ b/frontend/src/entities/need/model/query-keys.ts @@ -0,0 +1,22 @@ +import { + getGetOrganizationNeedQueryKey, + getListOrganizationNeedsQueryKey, +} from "../../../shared/api/endpoints/need/need"; +import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization"; + +export const needDirectoryPageSize = 100; +export const needListPageSize = 20; + +/** Need data stays separate for each signed-in account and organization. */ +export const needQueryKeys = { + directory: (accountId: string) => + [...getListMyOrganizationsQueryKey({ limit: needDirectoryPageSize }), accountId] as const, + list: (accountId: string, organizationId: string) => + [ + ...getListOrganizationNeedsQueryKey(organizationId, { limit: needListPageSize }), + accountId, + organizationId, + ] as const, + detail: (accountId: string, organizationId: string, needId: string) => + [...getGetOrganizationNeedQueryKey(organizationId, needId), accountId, organizationId] as const, +}; diff --git a/frontend/src/entities/need/model/rebase.ts b/frontend/src/entities/need/model/rebase.ts new file mode 100644 index 0000000..aa17ee3 --- /dev/null +++ b/frontend/src/entities/need/model/rebase.ts @@ -0,0 +1,25 @@ +import type { Need } from "../../../shared/api/schemas"; +import { changedNeedFields } from "./to-transport"; +import { fromTransport } from "./from-transport"; +import type { NeedFormField, NeedFormValues } from "./types"; + +function carryDraftField( + target: NeedFormValues, + source: NeedFormValues, + field: K, +): NeedFormValues { + return { ...target, [field]: source[field] }; +} + +/** Reapplies only locally changed fields over a newly loaded server version. */ +export function rebaseNeedDraft( + original: Need, + draft: NeedFormValues, + latest: Need, +): NeedFormValues { + const changedFields = new Set(changedNeedFields(original, draft)); + return (Object.keys(draft) as NeedFormField[]).reduce((rebased, field) => { + if (!changedFields.has(field)) return rebased; + return carryDraftField(rebased, draft, field); + }, fromTransport(latest)); +} diff --git a/frontend/src/entities/support-case/index.ts b/frontend/src/entities/support-case/index.ts new file mode 100644 index 0000000..73e1c22 --- /dev/null +++ b/frontend/src/entities/support-case/index.ts @@ -0,0 +1,18 @@ +export { createSupportCaseIdempotencyKey, getSupportCaseIdempotencyKey } from "./model/idempotency"; +export type { SupportCaseKeyBinding } from "./model/idempotency"; +export { parseSupportCaseContext, supportCaseContextLabel } from "./model/context"; +export { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./model/query-keys"; +export { queryClientHasSupportActor, supportSessionMatches } from "./model/session-guard"; +export { + isSupportSessionAccessError, + supportCaseCreateFailureMessage, + supportCasePathFor, +} from "./model/submission"; +export { + formatSupportDate, + supportCaseActorLabels, + supportCaseEventKindLabels, + supportCaseStatusLabels, + supportCaseTypeLabels, + supportTargetDescription, +} from "./model/presentation"; diff --git a/frontend/src/entities/support-case/model/context.test.ts b/frontend/src/entities/support-case/model/context.test.ts new file mode 100644 index 0000000..d0b8e80 --- /dev/null +++ b/frontend/src/entities/support-case/model/context.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { parseSupportCaseContext, supportCaseContextLabel } from "./context"; + +const attempt = { type: "assessment_attempt", id: "4c0ce905-a668-4f5d-961b-dc90fc4b684d" }; + +describe("support case context", () => { + it("accepts only the allowlisted object kind and UUID from router state", () => { + expect(parseSupportCaseContext(attempt)).toEqual(attempt); + expect(parseSupportCaseContext({ ...attempt, extra: "ignored" })).toEqual(attempt); + expect(parseSupportCaseContext({ type: "profile", id: attempt.id })).toBeNull(); + expect(parseSupportCaseContext({ ...attempt, id: "not-a-uuid" })).toBeNull(); + expect(parseSupportCaseContext(null)).toBeNull(); + }); + + it("uses a descriptive label without showing the reference identifier", () => { + const context = parseSupportCaseContext(attempt); + if (!context) throw new Error("Expected a valid context"); + expect(supportCaseContextLabel(context)).toBe("попыткой оценки"); + }); +}); diff --git a/frontend/src/entities/support-case/model/context.ts b/frontend/src/entities/support-case/model/context.ts new file mode 100644 index 0000000..a402c3c --- /dev/null +++ b/frontend/src/entities/support-case/model/context.ts @@ -0,0 +1,37 @@ +import type { SupportCaseObjectReference } from "../../../shared/api/schemas"; + +const allowedObjectTypes = new Set([ + "assessment_attempt", + "organization", + "invitation", + "support_case", +]); + +const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +export function parseSupportCaseContext(value: unknown): SupportCaseObjectReference | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const record = value as Record; + if ( + typeof record.type !== "string" || + !allowedObjectTypes.has(record.type as SupportCaseObjectReference["type"]) || + typeof record.id !== "string" || + !uuidPattern.test(record.id) + ) { + return null; + } + return { type: record.type as SupportCaseObjectReference["type"], id: record.id }; +} + +export function supportCaseContextLabel(context: SupportCaseObjectReference): string { + switch (context.type) { + case "assessment_attempt": + return "попыткой оценки"; + case "organization": + return "компанией"; + case "invitation": + return "приглашением"; + case "support_case": + return "другим обращением"; + } +} diff --git a/frontend/src/entities/support-case/model/idempotency.test.ts b/frontend/src/entities/support-case/model/idempotency.test.ts new file mode 100644 index 0000000..3207ca6 --- /dev/null +++ b/frontend/src/entities/support-case/model/idempotency.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it, vi } from "vitest"; +import type { SupportCaseCreate } from "../../../shared/api/schemas"; +import { getSupportCaseIdempotencyKey } from "./idempotency"; + +const body: SupportCaseCreate = { type: "support", description: "Нужна помощь" }; + +describe("support case idempotency key", () => { + it("keeps a key for an identical retry", () => { + const createKey = vi.fn(() => "case-key-1"); + const first = getSupportCaseIdempotencyKey(body, null, createKey); + const retry = getSupportCaseIdempotencyKey({ ...body }, first, createKey); + + expect(retry).toBe(first); + expect(retry.key).toBe("case-key-1"); + expect(createKey).toHaveBeenCalledOnce(); + }); + + it("rotates the key when the request body changes", () => { + const createKey = vi.fn().mockReturnValueOnce("case-key-1").mockReturnValueOnce("case-key-2"); + const first = getSupportCaseIdempotencyKey(body, null, createKey); + const changed = getSupportCaseIdempotencyKey( + { ...body, description: "Нужна другая помощь" }, + first, + createKey, + ); + + expect(changed.key).toBe("case-key-2"); + }); +}); diff --git a/frontend/src/entities/support-case/model/idempotency.ts b/frontend/src/entities/support-case/model/idempotency.ts new file mode 100644 index 0000000..b7fe086 --- /dev/null +++ b/frontend/src/entities/support-case/model/idempotency.ts @@ -0,0 +1,20 @@ +import type { SupportCaseCreate } from "../../../shared/api/schemas"; + +export type SupportCaseKeyBinding = { body: string; key: string }; + +export function getSupportCaseIdempotencyKey( + body: SupportCaseCreate, + previous: SupportCaseKeyBinding | null, + createKey: () => string, +): SupportCaseKeyBinding { + const serialized = JSON.stringify(body); + if (previous?.body === serialized) return previous; + return { body: serialized, key: createKey() }; +} + +export function createSupportCaseIdempotencyKey(): string { + if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") { + throw new Error("Secure random key generation is unavailable."); + } + return crypto.randomUUID(); +} diff --git a/frontend/src/entities/support-case/model/presentation.test.ts b/frontend/src/entities/support-case/model/presentation.test.ts new file mode 100644 index 0000000..7599441 --- /dev/null +++ b/frontend/src/entities/support-case/model/presentation.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { supportCaseStatusLabels, supportTargetDescription } from "./presentation"; + +describe("support case presentation", () => { + it("describes operational goals without presenting them as legal deadlines", () => { + expect( + supportTargetDescription({ + kind: "operational_goal", + business_days: 5, + due_at: "2026-10-13T09:00:00Z", + answered_at: null, + late: false, + policy_version: 2, + }), + ).toMatch(/операционная цель, не юридический срок/); + }); + + it("labels manual assessment as waiting for an expert", () => { + expect(supportCaseStatusLabels.waiting_expert).toBe("Ожидает эксперта"); + }); +}); diff --git a/frontend/src/entities/support-case/model/presentation.ts b/frontend/src/entities/support-case/model/presentation.ts new file mode 100644 index 0000000..5f7a74e --- /dev/null +++ b/frontend/src/entities/support-case/model/presentation.ts @@ -0,0 +1,68 @@ +import type { + SupportCaseActorKind, + SupportCaseEventKind, + SupportCaseStatus, + SupportCaseType, + SupportResponseTarget, +} from "../../../shared/api/schemas"; + +export const supportCaseTypeLabels: Readonly> = { + support: "Вопрос в поддержку", + complaint: "Жалоба", + grade_appeal: "Апелляция по оценке", + anticheat_appeal: "Апелляция по проверке безопасности", + manual_assessment: "Ручная оценка", +}; + +export const supportCaseStatusLabels: Readonly> = { + submitted: "Принято", + in_review: "Рассматривается", + waiting_for_user: "Нужен ваш ответ", + waiting_expert: "Ожидает эксперта", + resolved: "Решено", + closed: "Закрыто", +}; + +export const supportCaseEventKindLabels: Readonly> = { + created: "Обращение создано", + status_changed: "Статус изменен", + reply: "Ответ поддержки", + decision: "Решение", +}; + +export const supportCaseActorLabels: Readonly> = { + user: "Вы", + support: "Поддержка или эксперт", + system: "Система", +}; + +export function formatSupportDate(value: string): string { + const date = new Date(value); + if (Number.isNaN(date.valueOf())) return value; + return new Intl.DateTimeFormat("ru-RU", { + dateStyle: "medium", + timeStyle: "short", + }).format(date); +} + +export function supportTargetDescription(target: SupportResponseTarget): string { + const targetDate = formatSupportDate(target.due_at); + const period = `${target.business_days} ${businessDayLabel(target.business_days)}`; + if (target.answered_at) { + return `Первый ответ получен ${formatSupportDate(target.answered_at)}. Целевой период был ${period}.`; + } + if (target.late) { + return `Ориентир команды - до ${targetDate}; целевой период ${period} уже прошел.`; + } + return `Ориентир команды - до ${targetDate}, в течение ${period}. Это операционная цель, не юридический срок.`; +} + +function businessDayLabel(value: number): string { + const remainder = value % 10; + const hundredRemainder = value % 100; + if (remainder === 1 && hundredRemainder !== 11) return "рабочий день"; + if (remainder >= 2 && remainder <= 4 && (hundredRemainder < 12 || hundredRemainder > 14)) { + return "рабочих дня"; + } + return "рабочих дней"; +} diff --git a/frontend/src/entities/support-case/model/query-keys.test.ts b/frontend/src/entities/support-case/model/query-keys.test.ts new file mode 100644 index 0000000..e559a81 --- /dev/null +++ b/frontend/src/entities/support-case/model/query-keys.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./query-keys"; + +describe("support case query keys", () => { + it("separates private lists and details by account", () => { + expect(supportCaseListQueryKey("account-a")).not.toEqual(supportCaseListQueryKey("account-b")); + expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual( + supportCaseDetailQueryKey("account-b", "case-1"), + ); + }); + + it("separates case details within the same account", () => { + expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual( + supportCaseDetailQueryKey("account-a", "case-2"), + ); + }); +}); diff --git a/frontend/src/entities/support-case/model/query-keys.ts b/frontend/src/entities/support-case/model/query-keys.ts new file mode 100644 index 0000000..b38b8c2 --- /dev/null +++ b/frontend/src/entities/support-case/model/query-keys.ts @@ -0,0 +1,7 @@ +export function supportCaseListQueryKey(accountId: string) { + return ["account", accountId, "support-cases", "list"] as const; +} + +export function supportCaseDetailQueryKey(accountId: string, caseId: string) { + return ["account", accountId, "support-cases", "detail", caseId] as const; +} diff --git a/frontend/src/entities/support-case/model/session-guard.test.ts b/frontend/src/entities/support-case/model/session-guard.test.ts new file mode 100644 index 0000000..1164829 --- /dev/null +++ b/frontend/src/entities/support-case/model/session-guard.test.ts @@ -0,0 +1,63 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import type { Session } from "../../../shared/api/schemas"; +import { queryClientHasSupportActor, supportSessionMatches } from "./session-guard"; + +const session: Session = { + account: { + id: "22b209a8-8715-4ad5-a9b0-d93a18fc70a4", + email: "candidate@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "a".repeat(32), +}; + +const otherSession: Session = { + ...session, + account: { + ...session.account, + id: "36acbba3-d786-4c3a-95b2-4c374ab3206e", + }, + csrf_token: "b".repeat(32), +}; + +describe("support session guard", () => { + it("accepts the same account during a background refresh", () => { + const state = { + data: session, + status: "success", + fetchStatus: "fetching", + isInvalidated: true, + } as const; + + expect(supportSessionMatches(state, session)).toBe(true); + }); + + it("rejects cached session data once the session query errors", () => { + expect(supportSessionMatches({ data: session, status: "error" }, session)).toBe(false); + }); + + it("rejects another account and a rotated CSRF token", () => { + expect(supportSessionMatches({ data: otherSession, status: "success" }, session)).toBe(false); + expect( + supportSessionMatches( + { data: { ...session, csrf_token: "c".repeat(32) }, status: "success" }, + session, + ), + ).toBe(false); + }); + + it("reads the live session query state before allowing a callback to write", () => { + const queryClient = new QueryClient(); + const sessionKey = ["/api/v1/identity/sessions/current"]; + queryClient.setQueryData(sessionKey, session); + + expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(true); + + queryClient.setQueryData(sessionKey, otherSession); + expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(false); + }); +}); diff --git a/frontend/src/entities/support-case/model/session-guard.ts b/frontend/src/entities/support-case/model/session-guard.ts new file mode 100644 index 0000000..5ef2e9e --- /dev/null +++ b/frontend/src/entities/support-case/model/session-guard.ts @@ -0,0 +1,25 @@ +import type { QueryClient, QueryState } from "@tanstack/react-query"; +import type { Session } from "../../../shared/api/schemas"; + +type SessionSnapshot = Pick, "data" | "status">; + +export function supportSessionMatches( + snapshot: SessionSnapshot | undefined, + actor: Session, +): boolean { + return Boolean( + snapshot && + snapshot.status === "success" && + snapshot.data && + snapshot.data.account.id === actor.account.id && + snapshot.data.csrf_token === actor.csrf_token, + ); +} + +export function queryClientHasSupportActor( + queryClient: QueryClient, + sessionQueryKey: readonly unknown[], + actor: Session, +): boolean { + return supportSessionMatches(queryClient.getQueryState(sessionQueryKey), actor); +} diff --git a/frontend/src/entities/support-case/model/submission.test.ts b/frontend/src/entities/support-case/model/submission.test.ts new file mode 100644 index 0000000..276589b --- /dev/null +++ b/frontend/src/entities/support-case/model/submission.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import { supportCaseCreateFailureMessage } from "./submission"; + +describe("support case submission feedback", () => { + it("shows the server retry interval without retrying automatically", () => { + const message = supportCaseCreateFailureMessage( + new ApiRequestError({ + status: 429, + code: "rate_limited", + title: "Rate limited", + retryAfterSeconds: 15, + }), + ); + + expect(message).toContain("Повторите вручную через 15 сек."); + }); + + it("handles missing retry intervals and idempotency conflicts", () => { + expect( + supportCaseCreateFailureMessage( + new ApiRequestError({ status: 429, code: "rate_limited", title: "Rate limited" }), + ), + ).toContain("Попробуйте отправить обращение позже."); + expect( + supportCaseCreateFailureMessage( + new ApiRequestError({ + status: 422, + code: "idempotency_key_reused", + title: "Key reused", + }), + ), + ).toContain("Отправьте форму еще раз."); + }); +}); diff --git a/frontend/src/entities/support-case/model/submission.ts b/frontend/src/entities/support-case/model/submission.ts new file mode 100644 index 0000000..bafb017 --- /dev/null +++ b/frontend/src/entities/support-case/model/submission.ts @@ -0,0 +1,41 @@ +import { ApiRequestError } from "../../../shared/api"; +import type { Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; + +export function isSupportSessionAccessError(error: unknown): boolean { + return error instanceof ApiRequestError && (error.status === 401 || error.status === 403); +} + +export function supportCasePathFor(session: Session, caseId: string): string { + return session.account.scenario === "candidate" + ? paths.candidate.supportCase(caseId) + : paths.employer.supportCase(caseId); +} + +export function supportCaseCreateFailureMessage(error: unknown): string { + if (!(error instanceof ApiRequestError)) { + return "Не удалось отправить обращение. Проверьте соединение и повторите попытку."; + } + if (error.status === 429) { + const delay = error.retryAfterSeconds; + return delay === undefined + ? "Слишком много запросов. Попробуйте отправить обращение позже." + : `Слишком много запросов. Повторите вручную через ${delay} сек.`; + } + if (error.code === "idempotency_key_reused") { + return "Запрос уже связан с другой отправкой. Отправьте форму еще раз."; + } + if (error.code === "not_found") { + return "Не удалось подтвердить связанный объект. Проверьте его доступность и повторите отправку."; + } + if (error.code === "state_conflict") { + return "Действие конфликтует с текущим состоянием объекта. Обновите страницу и проверьте данные."; + } + if (error.code === "validation_failed") { + return "Проверьте текст обращения и выбранный контекст."; + } + if (error.status === 401 || error.status === 403) { + return "Сервер не подтвердил право отправить обращение. Обновите вход и повторите попытку."; + } + return "Не удалось отправить обращение. Попробуйте позже."; +} diff --git a/frontend/src/features/answer-assessment/index.ts b/frontend/src/features/answer-assessment/index.ts new file mode 100644 index 0000000..0063d30 --- /dev/null +++ b/frontend/src/features/answer-assessment/index.ts @@ -0,0 +1,5 @@ +export { AnswerForm } from "./ui/answer-form"; +export { buildAnswerSubmission, emptyAnswerDraft, newIdempotencyKey } from "./model/answer-draft"; +export { submitPendingAnswerCommand } from "./model/answer-command"; +export type { AnswerDraft, AnswerBuildResult } from "./model/answer-draft"; +export type { AnswerCommandOutcome, PendingAnswerCommand } from "./model/answer-command"; diff --git a/frontend/src/features/answer-assessment/model/answer-command.test.ts b/frontend/src/features/answer-assessment/model/answer-command.test.ts new file mode 100644 index 0000000..d5b0d60 --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-command.test.ts @@ -0,0 +1,156 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { AssessmentAttempt } from "../../../shared/api/schemas"; +import { submitPendingAnswerCommand, type PendingAnswerCommand } from "./answer-command"; + +const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01"; +const server = setupServer(); + +beforeAll(() => server.listen()); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +const validAttempt: AssessmentAttempt = { + id: attemptId, + version: 2, + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "python", + root_attempt_id: null, + chain_deadline: null, + mode: "demo_basic", + state: "in_progress", + versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" }, + started_at: "2026-10-08T10:00:00Z", + expires_at: "2026-10-08T11:00:00Z", + sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, + finished_at: null, + progress: { answered_items: 1, max_items: 2 }, + current_item: { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02", + sequence: 2, + prompt: "Сколько?", + content: { format: "number", unit: null }, + }, + practices: [], +}; + +describe("assessment answer response validation", () => { + it.each([{}, { id: attemptId, version: 2 }])( + "keeps the exact command retryable when a successful response is incomplete", + async (body) => { + const interceptedFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + interceptedFetch(new URL(input, "http://localhost"), init), + ); + const requests: Array<{ body: string | null; key: string | null; csrf: string | null }> = []; + server.use( + http.post( + `http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, + async ({ request }) => { + requests.push({ + body: await request.text(), + key: request.headers.get("Idempotency-Key"), + csrf: request.headers.get("X-CSRF-Token"), + }); + return HttpResponse.json(body, { status: 200 }); + }, + ), + ); + + const command: PendingAnswerCommand = { + key: "answer-command-key", + body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', + itemId: "item-1", + }; + const outcome = await submitPendingAnswerCommand(command, attemptId, "csrf-token"); + + expect(outcome.kind).toBe("retry"); + if (outcome.kind !== "retry") return; + expect(outcome.command).toBe(command); + expect(outcome.command).toEqual({ + key: "answer-command-key", + body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', + itemId: "item-1", + }); + expect(outcome.error).toMatchObject({ + status: 200, + code: invalidResponseCode, + } satisfies Partial); + expect(requests).toEqual([ + { + body: command.body, + key: command.key, + csrf: "csrf-token", + }, + ]); + }, + ); + + it("accepts a complete server attempt response", async () => { + const interceptedFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + interceptedFetch(new URL(input, "http://localhost"), init), + ); + server.use( + http.post(`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, () => + HttpResponse.json(validAttempt, { status: 200 }), + ), + ); + + const outcome = await submitPendingAnswerCommand( + { + key: "answer-command-key", + body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', + itemId: "item-1", + }, + attemptId, + "csrf-token", + ); + expect(outcome).toEqual({ kind: "accepted", attempt: validAttempt }); + }); + + it("replays the original key and body after a malformed success response", async () => { + const interceptedFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + interceptedFetch(new URL(input, "http://localhost"), init), + ); + const requests: Array<{ body: string; key: string | null }> = []; + let responseCount = 0; + server.use( + http.post( + `http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, + async ({ request }) => { + requests.push({ + body: await request.text(), + key: request.headers.get("Idempotency-Key"), + }); + responseCount += 1; + return HttpResponse.json(responseCount === 1 ? {} : validAttempt, { status: 200 }); + }, + ), + ); + const original: PendingAnswerCommand = { + key: "same-answer-key", + body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', + itemId: "item-1", + }; + + const first = await submitPendingAnswerCommand(original, attemptId, "csrf-token"); + expect(first.kind).toBe("retry"); + if (first.kind !== "retry") return; + const second = await submitPendingAnswerCommand(first.command, attemptId, "csrf-token"); + + expect(second).toEqual({ kind: "accepted", attempt: validAttempt }); + expect(requests).toEqual([ + { body: original.body, key: original.key }, + { body: original.body, key: original.key }, + ]); + }); +}); diff --git a/frontend/src/features/answer-assessment/model/answer-command.ts b/frontend/src/features/answer-assessment/model/answer-command.ts new file mode 100644 index 0000000..0252cf3 --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-command.ts @@ -0,0 +1,41 @@ +import { apiRequest } from "../../../shared/api"; +import { isOutcomeAmbiguous } from "../../../entities/assessment"; +import { getSubmitMyAssessmentAnswerUrl } from "../../../shared/api/endpoints/assessment/assessment"; +import { + AssessmentAttempt as assessmentAttemptSchema, + type AssessmentAttempt, +} from "../../../shared/api/schemas"; + +export type PendingAnswerCommand = { key: string; body: string; itemId: string }; + +export type AnswerCommandOutcome = + | { kind: "accepted"; attempt: AssessmentAttempt } + | { kind: "retry"; command: PendingAnswerCommand; error: unknown } + | { kind: "rejected"; error: unknown }; + +export async function submitPendingAnswerCommand( + command: PendingAnswerCommand, + attemptId: string, + csrfToken: string, +): Promise { + try { + const attempt = await apiRequest( + getSubmitMyAssessmentAnswerUrl(attemptId), + { + method: "POST", + headers: { + "Content-Type": "application/json", + "Idempotency-Key": command.key, + "X-CSRF-Token": csrfToken, + }, + body: command.body, + }, + assessmentAttemptSchema, + ); + return { kind: "accepted", attempt }; + } catch (error: unknown) { + return isOutcomeAmbiguous(error) + ? { kind: "retry", command, error } + : { kind: "rejected", error }; + } +} diff --git a/frontend/src/features/answer-assessment/model/answer-draft.test.ts b/frontend/src/features/answer-assessment/model/answer-draft.test.ts new file mode 100644 index 0000000..fe57d01 --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-draft.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "vitest"; +import type { AssessmentAttempt, AssessmentItem } from "../../../shared/api/schemas"; +import { buildAnswerSubmission, emptyAnswerDraft } from "./answer-draft"; + +const attempt = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01", + version: 4, + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "go", + root_attempt_id: null, + chain_deadline: null, + mode: "demo_basic", + state: "in_progress", + versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" }, + started_at: "2026-10-07T10:00:00Z", + expires_at: "2026-10-07T11:00:00Z", + sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, + finished_at: null, + progress: { answered_items: 0, max_items: 10 }, + current_item: null, + practices: [], +} satisfies AssessmentAttempt; + +const numberItem = { + id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02", + sequence: 1, + prompt: "Сколько?", + content: { format: "number", unit: null }, +} satisfies AssessmentItem; + +describe("assessment answer submission", () => { + it("preserves a decimal JSON token without converting it through JavaScript number", () => { + const token = "254.00000000000000000000000000000000000001"; + const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value: token }); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.submission).toBeNull(); + expect(result.body).toContain(`"number":${token}`); + expect(JSON.parse(result.body)).toMatchObject({ + expected_version: attempt.version, + item_id: numberItem.id, + }); + }); + + it.each([" 2", "2,5", "+2", "01", "Infinity", "2 "])( + "rejects a number token that is not valid JSON: %s", + (value) => { + const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value }); + + expect(result).toMatchObject({ ok: false }); + }, + ); + + it("keeps the initial order as a draft and requires a complete permutation", () => { + const item = { + id: numberItem.id, + sequence: 1, + prompt: "Упорядочите", + content: { + format: "order", + elements: [ + { id: "one", text: "Первый" }, + { id: "two", text: "Второй" }, + ], + }, + } satisfies AssessmentItem; + const draft = emptyAnswerDraft(item); + + expect(draft).toEqual({ format: "order", elementIds: ["one", "two"] }); + expect(buildAnswerSubmission(attempt, item, draft).ok).toBe(true); + expect( + buildAnswerSubmission(attempt, item, { format: "order", elementIds: ["one", "one"] }), + ).toMatchObject({ ok: false }); + }); +}); diff --git a/frontend/src/features/answer-assessment/model/answer-draft.ts b/frontend/src/features/answer-assessment/model/answer-draft.ts new file mode 100644 index 0000000..d774b83 --- /dev/null +++ b/frontend/src/features/answer-assessment/model/answer-draft.ts @@ -0,0 +1,145 @@ +import { AssessmentAnswerSubmission } from "../../../shared/api/schemas"; +import type { + AssessmentAttempt, + AssessmentItem, + AssessmentAnswerSubmission as AnswerSubmission, +} from "../../../shared/api/schemas"; + +export type AnswerDraft = + | { format: "choice"; optionIds: string[] } + | { format: "number"; value: string } + | { format: "string"; value: string } + | { format: "order"; elementIds: string[] } + | { format: "find_error"; lineNumbers: number[] } + | { format: "configuration"; value: string } + | { format: "practice"; language: "python" | "go" | null; sourceCode: string }; + +export type AnswerBuildResult = + { ok: true; body: string; submission: AnswerSubmission | null } | { ok: false; message: string }; + +const jsonNumberToken = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/; +const maxNumberTokenLength = 64; + +export function emptyAnswerDraft(item: AssessmentItem): AnswerDraft { + switch (item.content.format) { + case "choice": + return { format: "choice", optionIds: [] }; + case "number": + return { format: "number", value: "" }; + case "string": + return { format: "string", value: "" }; + case "order": + return { format: "order", elementIds: item.content.elements.map(({ id }) => id) }; + case "find_error": + return { format: "find_error", lineNumbers: [] }; + case "configuration": + return { format: "configuration", value: item.content.initial_config }; + case "practice": + return { format: "practice", language: item.content.languages[0] ?? null, sourceCode: "" }; + } +} + +export function buildAnswerSubmission( + attempt: AssessmentAttempt, + item: AssessmentItem, + draft: AnswerDraft, +): AnswerBuildResult { + if (draft.format !== item.content.format) { + return { ok: false, message: "Формат ответа не совпадает с заданием. Перезагрузите попытку." }; + } + + if (draft.format === "number" && item.content.format === "number") { + const token = draft.value; + if (token.length === 0) return { ok: false, message: "Введите числовой ответ." }; + if (token.length > maxNumberTokenLength || !jsonNumberToken.test(token)) { + return { + ok: false, + message: "Введите число без пробелов и разделителей тысяч. Десятичный разделитель - точка.", + }; + } + const body = `{"expected_version":${attempt.version},"item_id":${JSON.stringify(item.id)},"answer":{"format":"number","number":${token}}}`; + return { ok: true, body, submission: null }; + } + + let answer: AnswerSubmission["answer"] | null = null; + switch (draft.format) { + case "choice": + if (draft.optionIds.length === 0) { + return { ok: false, message: "Выберите ответ." }; + } + if ( + item.content.format === "choice" && + !item.content.multiple && + draft.optionIds.length !== 1 + ) { + return { ok: false, message: "Выберите один вариант." }; + } + answer = { format: "choice", option_ids: [...draft.optionIds] }; + break; + case "string": + if (draft.value.length === 0) return { ok: false, message: "Введите ответ." }; + if (item.content.format !== "string" || draft.value.length > item.content.max_length) { + return { ok: false, message: "Проверьте длину ответа." }; + } + answer = { format: "string", text: draft.value }; + break; + case "order": + if ( + item.content.format !== "order" || + draft.elementIds.length !== item.content.elements.length || + new Set(draft.elementIds).size !== item.content.elements.length || + item.content.elements.some(({ id }) => !draft.elementIds.includes(id)) + ) { + return { ok: false, message: "Расположите все элементы в нужном порядке." }; + } + answer = { format: "order", element_ids: [...draft.elementIds] }; + break; + case "find_error": + if ( + item.content.format !== "find_error" || + draft.lineNumbers.length === 0 || + draft.lineNumbers.length > item.content.max_selections + ) { + return { ok: false, message: "Выберите строки с ошибкой в пределах лимита." }; + } + answer = { format: "find_error", line_numbers: [...draft.lineNumbers] }; + break; + case "configuration": + if ( + item.content.format !== "configuration" || + draft.value.length === 0 || + draft.value.length > item.content.max_length + ) { + return { ok: false, message: "Введите конфигурацию в пределах указанного лимита." }; + } + answer = { format: "configuration", config: draft.value }; + break; + case "practice": + if ( + item.content.format !== "practice" || + draft.sourceCode.length === 0 || + draft.sourceCode.length > item.content.max_source_length || + (draft.language !== null && !item.content.languages.includes(draft.language)) + ) { + return { ok: false, message: "Добавьте решение в разрешенном формате." }; + } + answer = { format: "practice", language: draft.language, source_code: draft.sourceCode }; + break; + } + + if (!answer) return { ok: false, message: "Проверьте ответ и повторите отправку." }; + + const parsed = AssessmentAnswerSubmission.safeParse({ + expected_version: attempt.version, + item_id: item.id, + answer, + }); + if (!parsed.success) { + return { ok: false, message: "Проверьте ответ и повторите отправку." }; + } + return { ok: true, body: JSON.stringify(parsed.data), submission: parsed.data }; +} + +export function newIdempotencyKey(): string { + return crypto.randomUUID(); +} diff --git a/frontend/src/features/answer-assessment/ui/answer-form.module.css b/frontend/src/features/answer-assessment/ui/answer-form.module.css new file mode 100644 index 0000000..8b111fe --- /dev/null +++ b/frontend/src/features/answer-assessment/ui/answer-form.module.css @@ -0,0 +1,181 @@ +.form { + display: grid; + gap: var(--space-4); + min-width: 0; +} + +.fields, +.code-lines { + display: grid; + gap: var(--space-3); + min-width: 0; + margin: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); +} + +.legend, +.code-lines legend { + padding: 0 var(--space-2); + font-weight: var(--font-weight-bold); +} + +.options, +.practice { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.option, +.code-line { + display: flex; + align-items: flex-start; + gap: var(--space-3); + min-width: 0; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-s); + cursor: pointer; +} + +.option input, +.code-line input { + flex: 0 0 auto; + width: 1.2rem; + height: 1.2rem; + margin-block-start: 0.15rem; + accent-color: var(--color-accent); +} + +.field { + display: grid; + gap: var(--space-2); + min-width: 0; + font-weight: var(--font-weight-bold); +} + +.field input, +.field select, +.field textarea { + width: 100%; + min-width: 0; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-s); + color: var(--color-text); + background: var(--color-surface); + font: inherit; + font-weight: var(--font-weight-regular); +} + +.field textarea { + resize: vertical; + font-family: var(--font-mono); + line-height: var(--line-height-body); + overflow-wrap: anywhere; +} + +.field :is(input, select, textarea):focus-visible, +.option input:focus-visible, +.code-line input:focus-visible { + outline: var(--line-strong) solid var(--color-accent); + outline-offset: 2px; +} + +.hint { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); + font-weight: var(--font-weight-regular); +} + +.order { + display: grid; + gap: var(--space-3); + margin: 0; + padding: 0; + list-style: none; +} + +.order-item { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: var(--space-3); + min-width: 0; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-s); +} + +.order-actions, +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + align-items: center; +} + +.code-lines { + padding-inline: var(--space-3); +} + +.code-line { + align-items: baseline; + font-family: var(--font-mono); + overflow-wrap: anywhere; +} + +.line-number { + flex: 0 0 2.5rem; + color: var(--color-text-secondary); + text-align: end; + user-select: none; +} + +.code-line code { + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.examples { + display: grid; + gap: var(--space-2); + min-width: 0; + padding: var(--space-3); + background: var(--color-canvas); + border-radius: var(--radius-s); +} + +.examples h3, +.examples p { + margin: 0; +} + +.examples pre { + max-width: 100%; + margin: var(--space-1) 0 var(--space-3); + padding: var(--space-2); + overflow-x: auto; + background: var(--color-surface); + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.error { + margin: 0; + color: var(--color-danger); +} + +@media (width < 42rem) { + .fields { + padding: var(--space-3); + } + + .order-item { + align-items: flex-start; + } +} diff --git a/frontend/src/features/answer-assessment/ui/answer-form.tsx b/frontend/src/features/answer-assessment/ui/answer-form.tsx new file mode 100644 index 0000000..b0021c1 --- /dev/null +++ b/frontend/src/features/answer-assessment/ui/answer-form.tsx @@ -0,0 +1,281 @@ +import { useState, type FormEvent } from "react"; +import type { AssessmentItem } from "../../../shared/api/schemas"; +import { Button } from "../../../shared/ui"; +import { emptyAnswerDraft, type AnswerDraft } from "../model/answer-draft"; +import styles from "./answer-form.module.css"; + +type AnswerFormProps = { + item: AssessmentItem; + isSaving: boolean; + retryable: boolean; + errorMessage: string | null; + onSubmit: (draft: AnswerDraft) => void; + onRetry: () => void; +}; + +export function AnswerForm({ + item, + isSaving, + retryable, + errorMessage, + onSubmit, + onRetry, +}: AnswerFormProps) { + const [draft, setDraft] = useState(() => emptyAnswerDraft(item)); + const frozen = isSaving || retryable; + + function submit(event: FormEvent) { + event.preventDefault(); + if (frozen) return; + onSubmit(draft); + } + + return ( +
+
+ Ваш ответ + +
+ {errorMessage ? ( +

+ {errorMessage} +

+ ) : null} +
+ {retryable ? ( + + ) : ( + + )} +
+
+ ); +} + +type AnswerFieldsProps = { + item: AssessmentItem; + draft: AnswerDraft; + setDraft: (draft: AnswerDraft) => void; +}; + +function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) { + const content = item.content; + + switch (content.format) { + case "choice": { + const selected = draft.format === "choice" ? draft.optionIds : []; + return ( +
+ {content.options.map((option) => { + const checked = selected.includes(option.id); + return ( + + ); + })} +
+ ); + } + case "number": + return ( + + ); + case "string": + return ( + + ); + case "order": { + const ids = + draft.format === "order" ? draft.elementIds : content.elements.map(({ id }) => id); + const options = new Map(content.elements.map((element) => [element.id, element.text])); + function move(index: number, offset: -1 | 1) { + const nextIndex = index + offset; + if (nextIndex < 0 || nextIndex >= ids.length) return; + const next = [...ids]; + [next[index], next[nextIndex]] = [next[nextIndex] as string, next[index] as string]; + setDraft({ format: "order", elementIds: next }); + } + return ( +
    + {ids.map((id, index) => ( +
  1. + {options.get(id)} +
    + + +
    +
  2. + ))} +
+ ); + } + case "find_error": { + const selected = draft.format === "find_error" ? draft.lineNumbers : []; + return ( +
+ Отметьте строки с ошибкой + {content.lines.map((line) => ( + + ))} +

Можно отметить не более {content.max_selections} строк.

+
+ ); + } + case "configuration": + return ( +