feat: persist candidate questionnaires and enforce company quotas
This commit is contained in:
1 parent
73c7caa225
commit
3a61a8e8bb
51 files changed
+6280
-38
No files matched your search
@@ -40,4 +40,14 @@ The same `Idempotency-Key` and body replay the original `201` snapshot within 24
|
||||
|
||||
`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.
|
||||
|
||||
## 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.
|
||||
|
||||
Saving advances onboarding only from `candidate_questionnaire` to `candidate_assessment`, in the same transaction. Other saved steps stay unchanged. Consent settings do not yet complete the consent onboarding step.
|
||||
|
||||
The public specialization catalog derives readiness from the current published bank, current policy, and an immutable reviewed mapping tied to the exact category opening and published-family manifest. Legacy openings without a mapping remain unavailable. Policy changes or family retirement invalidate readiness until a new reviewed opening is made; previously saved answers remain readable. Operator names are self-declared review metadata, not an authenticated operator identity.
|
||||
|
||||
`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).
|
||||
|
||||
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
|
||||
@@ -40,4 +40,14 @@
|
||||
|
||||
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
|
||||
|
||||
## Анкета кандидата
|
||||
|
||||
Подтвержденный кандидат читает и заменяет собственную анкету через `GET/PUT /api/v1/me/questionnaire`. Анкета имеет отдельную версию и хранит самооценку, форматы работы, необязательные суммы опыта и одну или две специализации. Она не назначает подтвержденные грейды. Идентичный повтор возвращает сохраненную запись без повышения версии; измененное тело с устаревшей версией получает 412 согласно контракту API. Одновременные одинаковые записи также возвращают одну победившую запись.
|
||||
|
||||
Сохранение переводит onboarding только из `candidate_questionnaire` в `candidate_assessment` в той же транзакции. Другие сохраненные шаги не меняются. Настройки согласий пока не завершают шаг согласий в onboarding.
|
||||
|
||||
Публичный каталог специализаций определяет готовность по текущему опубликованному банку, текущей политике и неизменяемому решению проверки, связанному с конкретным открытием категории и составом опубликованных семейств. Старые открытия без такой связи остаются недоступными. Смена политики или отзыв семейства закрывает готовность до нового проверенного открытия; сохраненные ответы остаются читаемыми. Имена операторов являются заявленными метаданными проверки, а не аутентифицированной личностью оператора.
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` проверяет сохранность, изоляцию аккаунтов, конкурентные версии, откат, условный переход шага и изменение доступности банка. Хранилище квот компании и порядок его вызова описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md).
|
||||
|
||||
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
@@ -0,0 +1,228 @@
|
||||
-- +goose Up
|
||||
-- Candidate questionnaire answers and reviewed assessment catalog bindings.
|
||||
-- Questionnaire values are private, self-reported data; they never contain
|
||||
-- a confirmed grade or category.
|
||||
|
||||
-- The same small array checks are used by the contract tables below. Null
|
||||
-- elements are refused because COUNT(DISTINCT ...) excludes them.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_questionnaire_unique_text_array(input_values text[]) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$
|
||||
SELECT cardinality(input_values) = count(DISTINCT value)
|
||||
FROM unnest(input_values) AS values_list(value)
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_questionnaire_unique_lower_text_array(input_values text[]) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$
|
||||
SELECT cardinality(input_values) = count(DISTINCT lower(value))
|
||||
FROM unnest(input_values) AS values_list(value)
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- The aggregate row owns the optimistic-concurrency version and work context.
|
||||
CREATE TABLE candidate_questionnaires (
|
||||
user_id uuid NOT NULL,
|
||||
version bigint NOT NULL,
|
||||
work_formats text[] NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT candidate_questionnaires_pkey PRIMARY KEY (user_id),
|
||||
CONSTRAINT candidate_questionnaires_user_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT candidate_questionnaires_version_positive CHECK (version > 0),
|
||||
CONSTRAINT candidate_questionnaires_work_formats CHECK (
|
||||
cardinality(work_formats) BETWEEN 1 AND 3
|
||||
AND work_formats <@ ARRAY['remote', 'office', 'hybrid']::text[]
|
||||
AND candidate_questionnaire_unique_text_array(work_formats)
|
||||
),
|
||||
CONSTRAINT candidate_questionnaires_times_ordered CHECK (updated_at >= created_at)
|
||||
);
|
||||
|
||||
-- Stores the unique, ordered specialization answers separately from the
|
||||
-- candidate's assessment result and confirmed category.
|
||||
CREATE TABLE candidate_questionnaire_specializations (
|
||||
user_id uuid NOT NULL,
|
||||
ordinal smallint NOT NULL,
|
||||
specialization text NOT NULL,
|
||||
self_assessed_grade text NOT NULL,
|
||||
task_languages text[] NOT NULL,
|
||||
stack text[] NOT NULL,
|
||||
commercial_months integer,
|
||||
academic_months integer,
|
||||
CONSTRAINT candidate_questionnaire_specializations_pkey PRIMARY KEY (user_id, ordinal),
|
||||
CONSTRAINT candidate_questionnaire_specializations_user_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES candidate_questionnaires (user_id) ON DELETE CASCADE,
|
||||
CONSTRAINT candidate_questionnaire_specializations_unique_code UNIQUE (user_id, specialization),
|
||||
CONSTRAINT candidate_questionnaire_specializations_ordinal CHECK (ordinal BETWEEN 0 AND 1),
|
||||
CONSTRAINT candidate_questionnaire_specializations_code CHECK (
|
||||
specialization IN (
|
||||
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
|
||||
'data_analyst', 'ds_ml', 'information_security', 'qa'
|
||||
)
|
||||
),
|
||||
CONSTRAINT candidate_questionnaire_specializations_grade CHECK (
|
||||
self_assessed_grade IN ('intern', 'junior', 'middle', 'senior')
|
||||
),
|
||||
CONSTRAINT candidate_questionnaire_specializations_languages CHECK (
|
||||
cardinality(task_languages) <= 2
|
||||
AND task_languages <@ ARRAY['python', 'go']::text[]
|
||||
AND candidate_questionnaire_unique_text_array(task_languages)
|
||||
),
|
||||
CONSTRAINT candidate_questionnaire_specializations_stack CHECK (
|
||||
cardinality(stack) <= 20
|
||||
AND candidate_questionnaire_unique_lower_text_array(stack)
|
||||
),
|
||||
CONSTRAINT candidate_questionnaire_specializations_experience CHECK (
|
||||
(commercial_months IS NULL AND academic_months IS NULL)
|
||||
OR (
|
||||
commercial_months IS NOT NULL
|
||||
AND academic_months IS NOT NULL
|
||||
AND commercial_months BETWEEN 0 AND 600
|
||||
AND academic_months BETWEEN 0 AND 600
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- A catalog binding is an explicit operator-reviewed mapping for one immutable
|
||||
-- opening. The fingerprint pins it to the exact published family set present
|
||||
-- when the opening is made. Legacy openings have no row and stay unavailable
|
||||
-- in the public catalog.
|
||||
CREATE TABLE assessment_category_catalog_bindings (
|
||||
opening_id uuid NOT NULL,
|
||||
specialization text NOT NULL,
|
||||
grade text NOT NULL,
|
||||
task_languages text[] NOT NULL,
|
||||
published_manifest_sha256 bytea NOT NULL,
|
||||
reviewed_by text NOT NULL,
|
||||
reviewed_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_category_catalog_bindings_pkey PRIMARY KEY (opening_id),
|
||||
CONSTRAINT assessment_category_catalog_bindings_opening_fkey FOREIGN KEY (opening_id)
|
||||
REFERENCES assessment_category_openings (id),
|
||||
CONSTRAINT assessment_category_catalog_bindings_specialization CHECK (
|
||||
specialization IN (
|
||||
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
|
||||
'data_analyst', 'ds_ml', 'information_security', 'qa'
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_category_catalog_bindings_grade CHECK (
|
||||
grade IN ('intern', 'junior', 'middle', 'senior')
|
||||
),
|
||||
CONSTRAINT assessment_category_catalog_bindings_languages CHECK (
|
||||
cardinality(task_languages) <= 2
|
||||
AND task_languages <@ ARRAY['python', 'go']::text[]
|
||||
AND candidate_questionnaire_unique_text_array(task_languages)
|
||||
),
|
||||
CONSTRAINT assessment_category_catalog_bindings_manifest_hash CHECK (
|
||||
octet_length(published_manifest_sha256) = 32
|
||||
),
|
||||
CONSTRAINT assessment_category_catalog_bindings_reviewer CHECK (
|
||||
char_length(reviewed_by) <= 128
|
||||
AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
)
|
||||
);
|
||||
|
||||
-- Openings and published families are already immutable. Refuse a catalog
|
||||
-- mapping unless it names the current opening and the full reviewed bank still
|
||||
-- meets that opening's coverage and policy requirements.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_category_catalog_bindings_validate() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
opening assessment_category_openings%ROWTYPE;
|
||||
current_policy_id uuid;
|
||||
published_count integer;
|
||||
BEGIN
|
||||
SELECT * INTO opening
|
||||
FROM assessment_category_openings AS candidate
|
||||
WHERE candidate.id = NEW.opening_id;
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'foreign_key_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_opening',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog binding references an unknown opening';
|
||||
END IF;
|
||||
IF opening.opened_by <> NEW.reviewed_by THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_reviewer',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog binding reviewer must match the category opener';
|
||||
END IF;
|
||||
IF 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)
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_current_opening',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog binding must reference the current opening';
|
||||
END IF;
|
||||
SELECT policy.id INTO current_policy_id
|
||||
FROM policy_versions AS policy
|
||||
WHERE policy.policy_key = 'product' AND policy.effective_at <= clock_timestamp()
|
||||
ORDER BY policy.version DESC
|
||||
LIMIT 1;
|
||||
IF current_policy_id IS DISTINCT FROM opening.policy_version_id THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_policy_current',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog binding opening does not use the current policy';
|
||||
END IF;
|
||||
SELECT count(DISTINCT family.family_key)::integer INTO published_count
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published';
|
||||
IF published_count < opening.required_families THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_coverage',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog binding bank no longer meets its opening coverage';
|
||||
END IF;
|
||||
NEW.reviewed_at := clock_timestamp();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_category_catalog_bindings_validate
|
||||
BEFORE INSERT ON assessment_category_catalog_bindings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_category_catalog_bindings_validate();
|
||||
|
||||
-- A binding is an immutable review decision. It is replaced only by a new
|
||||
-- opening and a new binding, never edited in place.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_category_catalog_bindings_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_category_catalog_bindings_immutable',
|
||||
TABLE = 'assessment_category_catalog_bindings',
|
||||
MESSAGE = 'catalog bindings are immutable: create a new category opening';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_category_catalog_bindings_refuse_update_delete
|
||||
BEFORE UPDATE OR DELETE ON assessment_category_catalog_bindings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_category_catalog_bindings_refuse_change();
|
||||
|
||||
CREATE TRIGGER assessment_category_catalog_bindings_refuse_truncate
|
||||
BEFORE TRUNCATE ON assessment_category_catalog_bindings
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION assessment_category_catalog_bindings_refuse_change();
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE assessment_category_catalog_bindings;
|
||||
DROP FUNCTION assessment_category_catalog_bindings_refuse_change();
|
||||
DROP FUNCTION assessment_category_catalog_bindings_validate();
|
||||
DROP TABLE candidate_questionnaire_specializations;
|
||||
DROP TABLE candidate_questionnaires;
|
||||
DROP FUNCTION candidate_questionnaire_unique_lower_text_array(text[]);
|
||||
DROP FUNCTION candidate_questionnaire_unique_text_array(text[]);
|
||||
@@ -0,0 +1,106 @@
|
||||
-- +goose Up
|
||||
-- Invitation usage remains keyed by its stable invitation ID for the
|
||||
-- organization's lifetime, so a retry cannot count it again after the
|
||||
-- rolling window. The policy and trust columns record the basis of the
|
||||
-- original reservation.
|
||||
CREATE TABLE company_invitation_quota_usage (
|
||||
organization_id uuid NOT NULL,
|
||||
invitation_id uuid NOT NULL,
|
||||
reserved_at timestamptz NOT NULL,
|
||||
policy_version_id uuid NOT NULL,
|
||||
verification_level text NOT NULL,
|
||||
verification_basis text NOT NULL,
|
||||
verification_changed_at timestamptz NOT NULL,
|
||||
quota_tier text NOT NULL,
|
||||
CONSTRAINT company_invitation_quota_usage_pkey PRIMARY KEY (
|
||||
organization_id, invitation_id
|
||||
),
|
||||
CONSTRAINT company_invitation_quota_usage_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE CASCADE,
|
||||
CONSTRAINT company_invitation_quota_usage_policy_version_id_fkey FOREIGN KEY (
|
||||
policy_version_id
|
||||
) REFERENCES policy_versions (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT company_invitation_quota_usage_verification_evidence CHECK (
|
||||
(
|
||||
verification_level = 'e0'
|
||||
AND verification_basis = 'confirmed_email'
|
||||
) OR (
|
||||
verification_level = 'e1'
|
||||
AND verification_basis = 'corporate_domain'
|
||||
) OR (
|
||||
verification_level = 'e2'
|
||||
AND verification_basis = 'requisites_and_authority'
|
||||
)
|
||||
),
|
||||
CONSTRAINT company_invitation_quota_usage_tier_known CHECK (
|
||||
quota_tier IN ('e0', 'e1', 'e2')
|
||||
),
|
||||
CONSTRAINT company_invitation_quota_usage_tier_matches_verification CHECK (
|
||||
quota_tier = verification_level
|
||||
),
|
||||
CONSTRAINT company_invitation_quota_usage_verification_not_future CHECK (
|
||||
verification_changed_at <= reserved_at
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX company_invitation_quota_usage_window_idx
|
||||
ON company_invitation_quota_usage (organization_id, reserved_at, invitation_id);
|
||||
|
||||
-- Card-view rows are a rolling-window counter, not a full access history.
|
||||
-- Repeats update last_seen_at; expired rows may be deleted in bounded batches
|
||||
-- only after a successful reservation. This is logical window expiry, not a
|
||||
-- promise of deletion at an exact wall-clock time.
|
||||
CREATE TABLE company_card_view_quota_usage (
|
||||
organization_id uuid NOT NULL,
|
||||
candidate_id uuid NOT NULL,
|
||||
last_seen_at timestamptz NOT NULL,
|
||||
policy_version_id uuid NOT NULL,
|
||||
verification_level text NOT NULL,
|
||||
verification_basis text NOT NULL,
|
||||
verification_changed_at timestamptz NOT NULL,
|
||||
quota_tier text NOT NULL,
|
||||
CONSTRAINT company_card_view_quota_usage_pkey PRIMARY KEY (
|
||||
organization_id, candidate_id
|
||||
),
|
||||
CONSTRAINT company_card_view_quota_usage_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE CASCADE,
|
||||
CONSTRAINT company_card_view_quota_usage_candidate_id_fkey FOREIGN KEY (
|
||||
candidate_id
|
||||
) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT company_card_view_quota_usage_policy_version_id_fkey FOREIGN KEY (
|
||||
policy_version_id
|
||||
) REFERENCES policy_versions (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT company_card_view_quota_usage_verification_evidence CHECK (
|
||||
(
|
||||
verification_level = 'e0'
|
||||
AND verification_basis = 'confirmed_email'
|
||||
) OR (
|
||||
verification_level = 'e1'
|
||||
AND verification_basis = 'corporate_domain'
|
||||
) OR (
|
||||
verification_level = 'e2'
|
||||
AND verification_basis = 'requisites_and_authority'
|
||||
)
|
||||
),
|
||||
CONSTRAINT company_card_view_quota_usage_tier_known CHECK (
|
||||
quota_tier IN ('e0', 'e1', 'e2')
|
||||
),
|
||||
CONSTRAINT company_card_view_quota_usage_tier_matches_verification CHECK (
|
||||
quota_tier = verification_level
|
||||
),
|
||||
CONSTRAINT company_card_view_quota_usage_verification_not_future CHECK (
|
||||
verification_changed_at <= last_seen_at
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX company_card_view_quota_usage_window_idx
|
||||
ON company_card_view_quota_usage (organization_id, last_seen_at, candidate_id);
|
||||
|
||||
CREATE INDEX company_card_view_quota_usage_candidate_idx
|
||||
ON company_card_view_quota_usage (candidate_id);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE company_card_view_quota_usage;
|
||||
DROP TABLE company_invitation_quota_usage;
|
||||
@@ -0,0 +1,130 @@
|
||||
-- Writers lock the organization first, then invitation/card-view state, and
|
||||
-- finally usage rows. The organization lock serializes quota decisions for
|
||||
-- the tenant and makes the subsequent count and insert atomic.
|
||||
|
||||
-- name: LockCompanyQuotaOrganization :one
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at
|
||||
FROM organizations
|
||||
WHERE id = sqlc.arg(organization_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: FindCompanyInvitationQuotaUsage :one
|
||||
SELECT invitation_id
|
||||
FROM company_invitation_quota_usage
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND invitation_id = sqlc.arg(invitation_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: CountCompanyInvitationQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(reserved_at) AS earliest_at
|
||||
FROM company_invitation_quota_usage
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND reserved_at > sqlc.arg(window_start);
|
||||
|
||||
-- name: InsertCompanyInvitationQuotaUsage :exec
|
||||
INSERT INTO company_invitation_quota_usage (
|
||||
organization_id,
|
||||
invitation_id,
|
||||
reserved_at,
|
||||
policy_version_id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
quota_tier
|
||||
) VALUES (
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(invitation_id),
|
||||
sqlc.arg(reserved_at),
|
||||
sqlc.arg(policy_version_id),
|
||||
sqlc.arg(verification_level),
|
||||
sqlc.arg(verification_basis),
|
||||
sqlc.arg(verification_changed_at),
|
||||
sqlc.arg(quota_tier)
|
||||
);
|
||||
|
||||
-- name: FindCompanyCardViewQuotaUsage :one
|
||||
SELECT last_seen_at
|
||||
FROM company_card_view_quota_usage
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND candidate_id = sqlc.arg(candidate_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: RefreshCompanyCardViewQuotaUsage :execrows
|
||||
UPDATE company_card_view_quota_usage
|
||||
SET
|
||||
last_seen_at = greatest(last_seen_at, sqlc.arg(last_seen_at)),
|
||||
policy_version_id = sqlc.arg(policy_version_id),
|
||||
verification_level = sqlc.arg(verification_level),
|
||||
verification_basis = sqlc.arg(verification_basis),
|
||||
verification_changed_at = sqlc.arg(verification_changed_at),
|
||||
quota_tier = sqlc.arg(quota_tier)
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND candidate_id = sqlc.arg(candidate_id)
|
||||
AND last_seen_at > sqlc.arg(window_start);
|
||||
|
||||
-- name: CountCompanyCardViewQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(last_seen_at) AS earliest_at
|
||||
FROM company_card_view_quota_usage
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND last_seen_at > sqlc.arg(window_start);
|
||||
|
||||
-- name: SaveCompanyCardViewQuotaUsage :exec
|
||||
INSERT INTO company_card_view_quota_usage (
|
||||
organization_id,
|
||||
candidate_id,
|
||||
last_seen_at,
|
||||
policy_version_id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
quota_tier
|
||||
) VALUES (
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(candidate_id),
|
||||
sqlc.arg(last_seen_at),
|
||||
sqlc.arg(policy_version_id),
|
||||
sqlc.arg(verification_level),
|
||||
sqlc.arg(verification_basis),
|
||||
sqlc.arg(verification_changed_at),
|
||||
sqlc.arg(quota_tier)
|
||||
)
|
||||
ON CONFLICT (organization_id, candidate_id)
|
||||
DO UPDATE SET
|
||||
last_seen_at = greatest(
|
||||
company_card_view_quota_usage.last_seen_at,
|
||||
EXCLUDED.last_seen_at
|
||||
),
|
||||
policy_version_id = EXCLUDED.policy_version_id,
|
||||
verification_level = EXCLUDED.verification_level,
|
||||
verification_basis = EXCLUDED.verification_basis,
|
||||
verification_changed_at = EXCLUDED.verification_changed_at,
|
||||
quota_tier = EXCLUDED.quota_tier;
|
||||
|
||||
-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows
|
||||
WITH expired AS (
|
||||
SELECT quota_usage.organization_id, quota_usage.candidate_id
|
||||
FROM company_card_view_quota_usage AS quota_usage
|
||||
WHERE
|
||||
quota_usage.organization_id = sqlc.arg(organization_id)
|
||||
AND quota_usage.last_seen_at <= sqlc.arg(window_start)
|
||||
ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id
|
||||
LIMIT sqlc.arg(row_limit)::integer
|
||||
)
|
||||
DELETE FROM company_card_view_quota_usage AS usage
|
||||
USING expired
|
||||
WHERE
|
||||
usage.organization_id = expired.organization_id
|
||||
AND usage.candidate_id = expired.candidate_id;
|
||||
@@ -0,0 +1,181 @@
|
||||
-- Creates the first saved questionnaire. A missing row is version zero;
|
||||
-- concurrent first saves race on the primary key and exactly one returns a row.
|
||||
-- name: InsertCandidateQuestionnaire :one
|
||||
INSERT INTO candidate_questionnaires (
|
||||
user_id,
|
||||
version,
|
||||
work_formats,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(user_id),
|
||||
1,
|
||||
sqlc.arg(work_formats),
|
||||
sqlc.arg(at)::timestamptz,
|
||||
sqlc.arg(at)::timestamptz
|
||||
)
|
||||
ON CONFLICT (user_id) DO NOTHING
|
||||
RETURNING user_id, version, work_formats, created_at, updated_at;
|
||||
|
||||
-- Advances an existing questionnaire only at the version read by the caller.
|
||||
-- The row lock serializes saves for one user; a stale writer returns no row.
|
||||
-- name: AdvanceCandidateQuestionnaireVersion :one
|
||||
UPDATE candidate_questionnaires
|
||||
SET
|
||||
version = candidate_questionnaires.version + 1,
|
||||
work_formats = sqlc.arg(work_formats),
|
||||
updated_at = GREATEST(candidate_questionnaires.updated_at, sqlc.arg(at)::timestamptz)
|
||||
WHERE
|
||||
candidate_questionnaires.user_id = sqlc.arg(user_id)
|
||||
AND candidate_questionnaires.version = sqlc.arg(expected_version)
|
||||
RETURNING user_id, version, work_formats, created_at, updated_at;
|
||||
|
||||
-- Reads the aggregate and its ordered specializations in one statement so a
|
||||
-- response never pairs a version with another version's answers.
|
||||
-- name: ReadCandidateQuestionnaire :one
|
||||
SELECT
|
||||
questionnaire.user_id,
|
||||
questionnaire.version,
|
||||
questionnaire.work_formats,
|
||||
questionnaire.created_at,
|
||||
questionnaire.updated_at,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'ordinal', specialization.ordinal,
|
||||
'specialization', specialization.specialization,
|
||||
'self_assessed_grade', specialization.self_assessed_grade,
|
||||
'task_languages', specialization.task_languages,
|
||||
'stack', specialization.stack,
|
||||
'commercial_months', specialization.commercial_months,
|
||||
'academic_months', specialization.academic_months
|
||||
) ORDER BY specialization.ordinal
|
||||
)
|
||||
FROM candidate_questionnaire_specializations AS specialization
|
||||
WHERE specialization.user_id = questionnaire.user_id
|
||||
), '[]'::jsonb)::text AS specializations
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
WHERE questionnaire.user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Replaces all specialization answers after the version row advanced in the
|
||||
-- same transaction.
|
||||
-- name: DeleteCandidateQuestionnaireSpecializations :exec
|
||||
DELETE FROM candidate_questionnaire_specializations
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: InsertCandidateQuestionnaireSpecialization :exec
|
||||
INSERT INTO candidate_questionnaire_specializations (
|
||||
user_id,
|
||||
ordinal,
|
||||
specialization,
|
||||
self_assessed_grade,
|
||||
task_languages,
|
||||
stack,
|
||||
commercial_months,
|
||||
academic_months
|
||||
) VALUES (
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(specialization),
|
||||
sqlc.arg(self_assessed_grade),
|
||||
sqlc.arg(task_languages),
|
||||
sqlc.arg(stack),
|
||||
sqlc.narg(commercial_months),
|
||||
sqlc.narg(academic_months)
|
||||
);
|
||||
|
||||
-- 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.
|
||||
-- name: InsertAssessmentCategoryCatalogBinding :exec
|
||||
INSERT INTO assessment_category_catalog_bindings (
|
||||
opening_id,
|
||||
specialization,
|
||||
grade,
|
||||
task_languages,
|
||||
published_manifest_sha256,
|
||||
reviewed_by,
|
||||
reviewed_at
|
||||
) VALUES (
|
||||
sqlc.arg(opening_id),
|
||||
sqlc.arg(specialization),
|
||||
sqlc.arg(grade),
|
||||
sqlc.arg(task_languages),
|
||||
sqlc.arg(published_manifest_sha256),
|
||||
sqlc.arg(reviewed_by),
|
||||
clock_timestamp()
|
||||
);
|
||||
|
||||
-- Lists the exact published bank manifest while the category advisory lock is
|
||||
-- held by OpenCategory. Published families have passed the independent-review
|
||||
-- constraint before this read.
|
||||
-- name: ReadPublishedAssessmentCategoryManifest :many
|
||||
SELECT family_key, version, content_sha256
|
||||
FROM assessment_families
|
||||
WHERE category = sqlc.arg(category) AND lifecycle = 'published'
|
||||
ORDER BY family_key, version;
|
||||
|
||||
-- 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.
|
||||
-- name: ListCurrentSpecializationAvailability :many
|
||||
WITH current_policy AS (
|
||||
SELECT id
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
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,
|
||||
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 opening.category;
|
||||
|
||||
-- A questionnaire save advances onboarding only from its own step.
|
||||
-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec
|
||||
UPDATE users
|
||||
SET
|
||||
onboarding_step = 'candidate_assessment',
|
||||
version = users.version + 1,
|
||||
updated_at = GREATEST(users.updated_at, sqlc.arg(at)::timestamptz)
|
||||
WHERE
|
||||
users.id = sqlc.arg(user_id)
|
||||
AND users.scenario = 'candidate'
|
||||
AND users.email_verified_at IS NOT NULL
|
||||
AND users.onboarding_step = 'candidate_questionnaire';
|
||||
@@ -0,0 +1,529 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const companyQuotaTestTimeout = 5 * time.Minute
|
||||
|
||||
type companyQuotaFixture struct {
|
||||
ctx context.Context
|
||||
pool *pgxpool.Pool
|
||||
clock *testClock
|
||||
transactor *postgresadapter.Transactor
|
||||
service *companyquota.Service
|
||||
organizations organizationFixture
|
||||
policies outbound.PolicyRepository
|
||||
version domain.PolicyVersion
|
||||
}
|
||||
|
||||
func TestCompanyQuota(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
|
||||
clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)}
|
||||
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
organizationFixture := organizationFixture{
|
||||
ctx: ctx, pool: pool, identity: identity, transactor: transactor, now: clock.Now(),
|
||||
}
|
||||
policyStore := postgresadapter.NewPolicyStore(pool)
|
||||
if _, err := policy.NewPublisher(policyStore.Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
||||
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
||||
}
|
||||
version, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("GetEffective(product) error = %v", err)
|
||||
}
|
||||
fixture := companyQuotaFixture{
|
||||
ctx: ctx, pool: pool, clock: clock, transactor: transactor,
|
||||
service: companyquota.NewService(clock.Now), organizations: organizationFixture,
|
||||
policies: policyStore.Policies(), version: version,
|
||||
}
|
||||
|
||||
t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0)
|
||||
var firstCandidate uuid.UUID
|
||||
var boundaryCandidate uuid.UUID
|
||||
for range 9 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
}
|
||||
for index := range 49 {
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
if index == 0 {
|
||||
firstCandidate = candidateID
|
||||
} else if index == 1 {
|
||||
boundaryCandidate = candidateID
|
||||
}
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
decision outbound.CompanyQuotaDecision
|
||||
err error
|
||||
kind string
|
||||
}
|
||||
start := make(chan struct{})
|
||||
results := make(chan result, 4)
|
||||
var workers sync.WaitGroup
|
||||
for range 2 {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
decision, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
results <- result{decision: decision, err: err, kind: "invitation"}
|
||||
}()
|
||||
}
|
||||
for range 2 {
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
results <- result{decision: decision, err: err, kind: "view"}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
close(results)
|
||||
|
||||
allowedInvitations, deniedInvitations := 0, 0
|
||||
allowedViews, deniedViews := 0, 0
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("concurrent quota reservation error = %v", result.err)
|
||||
}
|
||||
switch result.kind {
|
||||
case "invitation":
|
||||
if result.decision.Allowed && result.decision.RetryAt.IsZero() {
|
||||
allowedInvitations++
|
||||
} else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) {
|
||||
deniedInvitations++
|
||||
} else {
|
||||
t.Fatalf("unexpected invitation decision: %+v", result.decision)
|
||||
}
|
||||
case "view":
|
||||
if result.decision.Allowed && result.decision.RetryAt.IsZero() {
|
||||
allowedViews++
|
||||
} else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) {
|
||||
deniedViews++
|
||||
} else {
|
||||
t.Fatalf("unexpected card-view decision: %+v", result.decision)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected reservation kind %q", result.kind)
|
||||
}
|
||||
}
|
||||
if allowedInvitations != 1 || deniedInvitations != 1 || allowedViews != 1 || deniedViews != 1 {
|
||||
t.Fatalf("concurrent invitation/view results: allowed=%d/%d denied=%d/%d", allowedInvitations, allowedViews, deniedInvitations, deniedViews)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 10, 50)
|
||||
fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail)
|
||||
|
||||
// A repeated card in the active window is shared by the organization.
|
||||
fixture.clock.Advance(23 * time.Hour)
|
||||
repeated, err := fixture.reserveCardView(organization, firstCandidate)
|
||||
if err != nil || !repeated.Allowed || !repeated.Reused {
|
||||
t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an organization-level reuse", repeated, err)
|
||||
}
|
||||
fixture.clock.Set(fixture.clock.Now().Add(time.Hour))
|
||||
atDay := fixture.clock.Now()
|
||||
for _, step := range []struct {
|
||||
name string
|
||||
id uuid.UUID
|
||||
call func(domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
}{
|
||||
{name: "card view at the 24-hour boundary", id: boundaryCandidate, call: fixture.reserveCardView},
|
||||
{name: "invitation remains charged during the first day", id: uuid.New(), call: fixture.reserveInvitation},
|
||||
} {
|
||||
decision, err := step.call(organization, step.id)
|
||||
if err != nil {
|
||||
t.Fatalf("%s error = %v", step.name, err)
|
||||
}
|
||||
if step.name == "card view at the 24-hour boundary" {
|
||||
if !decision.Allowed || decision.Reused {
|
||||
t.Fatalf("%s decision = %+v, want a new allowed view", step.name, decision)
|
||||
}
|
||||
} else if decision.Allowed || !decision.RetryAt.Equal(atDay.Add(6*24*time.Hour)) {
|
||||
t.Fatalf("%s decision = %+v, want retry at the 7-day boundary", step.name, decision)
|
||||
}
|
||||
}
|
||||
fixture.assertActiveQuotaCounts(t, organization.ID(), atDay, 10, 2)
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 10, 2)
|
||||
|
||||
fixture.clock.Set(atDay.Add(6 * 24 * time.Hour))
|
||||
newInvitation := uuid.New()
|
||||
decision, err := fixture.reserveInvitation(organization, newInvitation)
|
||||
if err != nil || !decision.Allowed || decision.Reused {
|
||||
t.Fatalf("ReserveInvitation(at 7 days) = %+v, %v; want a new allowed invitation", decision, err)
|
||||
}
|
||||
fixture.assertActiveQuotaCounts(t, organization.ID(), fixture.clock.Now(), 1, 0)
|
||||
|
||||
// The same invitation ID stays idempotent beyond the rolling window,
|
||||
// independently of any request idempotency key used by its caller.
|
||||
oldInvitationID := uuid.New()
|
||||
fixture.reserveInvitationAllowed(t, organization, oldInvitationID)
|
||||
fixture.clock.Advance(8 * 24 * time.Hour)
|
||||
reused, err := fixture.reserveInvitation(organization, oldInvitationID)
|
||||
if err != nil || !reused.Allowed || !reused.Reused {
|
||||
t.Fatalf("ReserveInvitation(old ID after 8 days) = %+v, %v; want retained idempotent usage", reused, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("E1 enforces the stored 40 and 150 limits", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "e1-boundary", domain.OrganizationVerificationE1)
|
||||
for range 40 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
}
|
||||
deniedInvitation, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
if err != nil || deniedInvitation.Allowed || !deniedInvitation.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) {
|
||||
t.Fatalf("E1 invitation 41 = %+v, %v; want denial for one week", deniedInvitation, err)
|
||||
}
|
||||
for range 150 {
|
||||
fixture.reserveCardViewAllowed(t, organization, fixture.newCandidateID(t))
|
||||
}
|
||||
deniedView, err := fixture.reserveCardView(organization, fixture.newCandidateID(t))
|
||||
if err != nil || deniedView.Allowed || !deniedView.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) {
|
||||
t.Fatalf("E1 card view 151 = %+v, %v; want denial for 24 hours", deniedView, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 40, 150)
|
||||
fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain)
|
||||
})
|
||||
|
||||
t.Run("active E2 policy permits verified organizations and rejects a forged tier snapshot", func(t *testing.T) {
|
||||
policyDocument := domain.DemoProductPolicyV1()
|
||||
policyDocument.OrganizationQuotas.TierE2.Active = true
|
||||
activePolicy, err := policy.NewPublisher(fixture.policies, fixture.clock.Now).Publish(fixture.ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test",
|
||||
EffectiveAt: fixture.clock.Now(), Policy: policyDocument,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish active E2 policy: %v", err)
|
||||
}
|
||||
if quota := activePolicy.Policy().OrganizationQuotas.TierE2; !quota.Active ||
|
||||
quota.InvitationsPerWindow != 100 || quota.DistinctCardViewsPerWindow != 400 {
|
||||
t.Fatalf("active E2 policy limits = %+v, want 100 invitations and 400 views", quota)
|
||||
}
|
||||
fixture.version = activePolicy
|
||||
|
||||
verified, _ := fixture.newOrganization(t, "active-e2", domain.OrganizationVerificationE2)
|
||||
invitation, err := fixture.reserveInvitation(verified, uuid.New())
|
||||
if err != nil || !invitation.Allowed || invitation.Reused {
|
||||
t.Fatalf("ReserveInvitation(verified E2) = %+v, %v; want an allowed new reservation", invitation, err)
|
||||
}
|
||||
view, err := fixture.reserveCardView(verified, fixture.newCandidateID(t))
|
||||
if err != nil || !view.Allowed || view.Reused {
|
||||
t.Fatalf("ReserveCardView(verified E2) = %+v, %v; want an allowed new reservation", view, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, verified.ID(), 1, 1)
|
||||
fixture.assertStoredEvidence(t, verified.ID(), domain.OrganizationVerificationE2, domain.OrganizationBasisRequisitesAndAuthority)
|
||||
|
||||
e0Organization, _ := fixture.newOrganization(t, "forged-e2", domain.OrganizationVerificationE0)
|
||||
forgedE2, err := domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: e0Organization.ID(), Name: e0Organization.Profile().Name(),
|
||||
VerificationLevel: string(domain.OrganizationVerificationE2),
|
||||
VerificationBasis: string(domain.OrganizationBasisRequisitesAndAuthority),
|
||||
VerificationChangedAt: fixture.clock.Now().Add(-time.Minute),
|
||||
Version: e0Organization.Version(), CreatedAt: e0Organization.CreatedAt(), UpdatedAt: e0Organization.UpdatedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("restore forged E2 snapshot for E0 organization: %v", err)
|
||||
}
|
||||
forgedQuota, err := domain.NewCompanyQuota(forgedE2, activePolicy, fixture.clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("build forged E2 snapshot: %v", err)
|
||||
}
|
||||
if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, uuid.New()); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with forged E2 snapshot against stored E0 organization error = %v, want snapshot mismatch", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, e0Organization.ID(), 0, 0)
|
||||
})
|
||||
|
||||
t.Run("a repeated view refreshes monotonically when application time moves backward", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "view-clock", domain.OrganizationVerificationE0)
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
firstSeen := fixture.clock.Now()
|
||||
fixture.clock.Advance(time.Hour)
|
||||
fixture.reserveCardViewReused(t, organization, candidateID)
|
||||
fixture.clock.Set(firstSeen.Add(30 * time.Minute))
|
||||
fixture.reserveCardViewReused(t, organization, candidateID)
|
||||
|
||||
var lastSeen time.Time
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT last_seen_at FROM company_card_view_quota_usage
|
||||
WHERE organization_id = $1 AND candidate_id = $2`, organization.ID(), candidateID).Scan(&lastSeen); err != nil {
|
||||
t.Fatalf("read repeated view timestamp: %v", err)
|
||||
}
|
||||
if !lastSeen.Equal(firstSeen.Add(time.Hour)) {
|
||||
t.Fatalf("last_seen_at = %s, want monotonic time %s", lastSeen, firstSeen.Add(time.Hour))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("candidate deletion clears card-view data but leaves invitation quota evidence", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "candidate-delete", domain.OrganizationVerificationE0)
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
fixture.reserveInvitationAllowed(t, organization, candidateID)
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM users WHERE id = $1`, candidateID); err != nil {
|
||||
t.Fatalf("delete candidate: %v", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 1, 0)
|
||||
})
|
||||
|
||||
t.Run("rollback and stale trust or policy snapshots write no usage", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "snapshot-check", domain.OrganizationVerificationE0)
|
||||
quota := fixture.quota(t, organization, fixture.version)
|
||||
rollbackMarker := errors.New("test transaction rollback")
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, uuid.New())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return errors.New("test invitation was unexpectedly denied")
|
||||
}
|
||||
return rollbackMarker
|
||||
})
|
||||
if !errors.Is(err, rollbackMarker) {
|
||||
t.Fatalf("transaction rollback error = %v, want marker", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `
|
||||
UPDATE organizations
|
||||
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
|
||||
WHERE id = $1`, organization.ID(), fixture.clock.Now().Add(-time.Minute)); err != nil {
|
||||
t.Fatalf("change stored organization verification: %v", err)
|
||||
}
|
||||
staleTrustErr := fixture.reserveWithSnapshot(organization, quota, uuid.New())
|
||||
if !errors.Is(staleTrustErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale organization trust error = %v, want snapshot mismatch", staleTrustErr)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
|
||||
policyOrganization, _ := fixture.newOrganization(t, "policy-check", domain.OrganizationVerificationE0)
|
||||
stalePolicyQuota := fixture.quota(t, policyOrganization, fixture.version)
|
||||
publisher := policy.NewPublisher(fixture.policies, fixture.clock.Now)
|
||||
_, err = publisher.Publish(fixture.ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test",
|
||||
EffectiveAt: fixture.clock.Now(), Policy: domain.DemoProductPolicyV1(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish next effective product policy: %v", err)
|
||||
}
|
||||
stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, uuid.New())
|
||||
if !errors.Is(stalePolicyErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale policy error = %v, want snapshot mismatch", stalePolicyErr)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, policyOrganization.ID(), 0, 0)
|
||||
})
|
||||
|
||||
t.Run("inactive E2 and E3 fail closed before recording usage", func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
level domain.OrganizationVerificationLevel
|
||||
basis domain.OrganizationVerificationBasis
|
||||
}{
|
||||
{name: "inactive E2", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority},
|
||||
{name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "denied-"+string(test.level), test.level)
|
||||
_, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("ReserveInvitation(%s) error = %v, want fail-closed denial", test.level, err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) newOrganization(
|
||||
t *testing.T,
|
||||
name string,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
) (domain.Organization, domain.User) {
|
||||
t.Helper()
|
||||
owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString()))
|
||||
organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute))
|
||||
if level != domain.OrganizationVerificationE0 {
|
||||
basis := domain.OrganizationBasisCorporateDomain
|
||||
switch level {
|
||||
case domain.OrganizationVerificationE2:
|
||||
basis = domain.OrganizationBasisRequisitesAndAuthority
|
||||
case domain.OrganizationVerificationE3:
|
||||
basis = domain.OrganizationBasisManualReview
|
||||
}
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `
|
||||
UPDATE organizations
|
||||
SET verification_level = $2, verification_basis = $3, verification_changed_at = $4
|
||||
WHERE id = $1`, organization.ID(), string(level), string(basis), fixture.clock.Now().Add(-time.Minute)); err != nil {
|
||||
t.Fatalf("set %s verification fixture: %v", level, err)
|
||||
}
|
||||
}
|
||||
stored, _, err := fixture.organizations.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("read %s organization: %v", level, err)
|
||||
}
|
||||
return stored, owner
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) newCandidateID(t *testing.T) uuid.UUID {
|
||||
t.Helper()
|
||||
candidate := fixture.organizations.identity.createUser(
|
||||
t,
|
||||
fmt.Sprintf("quota-candidate-%s@example.test", uuid.NewString()),
|
||||
domain.ScenarioCandidate,
|
||||
fixture.clock.Now().Add(-time.Hour),
|
||||
)
|
||||
return candidate.ID
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) quota(t *testing.T, organization domain.Organization, version domain.PolicyVersion) domain.CompanyQuota {
|
||||
t.Helper()
|
||||
quota, err := domain.NewCompanyQuota(organization, version, fixture.clock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota() error = %v", err)
|
||||
}
|
||||
return quota
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveInvitation(organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
var decision outbound.CompanyQuotaDecision
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID)
|
||||
return err
|
||||
})
|
||||
return decision, err
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardView(organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
var decision outbound.CompanyQuotaDecision
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
return err
|
||||
})
|
||||
return decision, err
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveWithSnapshot(organization domain.Organization, quota domain.CompanyQuota, invitationID uuid.UUID) error {
|
||||
return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, invitationID)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveInvitationAllowed(t *testing.T, organization domain.Organization, invitationID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveInvitation(organization, invitationID)
|
||||
if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveInvitation() = %+v, %v; want a new allowed reservation", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardViewAllowed(t *testing.T, organization domain.Organization, candidateID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveCardView() = %+v, %v; want a new allowed reservation", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) reserveCardViewReused(t *testing.T, organization domain.Organization, candidateID uuid.UUID) {
|
||||
t.Helper()
|
||||
decision, err := fixture.reserveCardView(organization, candidateID)
|
||||
if err != nil || !decision.Allowed || !decision.Reused || !decision.RetryAt.IsZero() {
|
||||
t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an allowed reuse", decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertQuotaRowCounts(t *testing.T, organizationID uuid.UUID, invitations, views int64) {
|
||||
t.Helper()
|
||||
var gotInvitations, gotViews int64
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotInvitations); err != nil {
|
||||
t.Fatalf("count invitation quota rows: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotViews); err != nil {
|
||||
t.Fatalf("count card-view quota rows: %v", err)
|
||||
}
|
||||
if gotInvitations != invitations || gotViews != views {
|
||||
t.Fatalf("quota rows for organization = invitations %d, views %d; want %d/%d", gotInvitations, gotViews, invitations, views)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertActiveQuotaCounts(t *testing.T, organizationID uuid.UUID, at time.Time, invitations, views int64) {
|
||||
t.Helper()
|
||||
var gotInvitations, gotViews int64
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_invitation_quota_usage
|
||||
WHERE organization_id = $1 AND reserved_at > $2`, organizationID, at.Add(-7*24*time.Hour)).Scan(&gotInvitations); err != nil {
|
||||
t.Fatalf("count active invitation quota rows: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT count(*) FROM company_card_view_quota_usage
|
||||
WHERE organization_id = $1 AND last_seen_at > $2`, organizationID, at.Add(-24*time.Hour)).Scan(&gotViews); err != nil {
|
||||
t.Fatalf("count active card-view quota rows: %v", err)
|
||||
}
|
||||
if gotInvitations != invitations || gotViews != views {
|
||||
t.Fatalf("active quota rows at %s = invitations %d, views %d; want %d/%d", at, gotInvitations, gotViews, invitations, views)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) assertStoredEvidence(
|
||||
t *testing.T,
|
||||
organizationID uuid.UUID,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
basis domain.OrganizationVerificationBasis,
|
||||
) {
|
||||
t.Helper()
|
||||
var invitationPolicy, viewPolicy uuid.UUID
|
||||
var invitationLevel, viewLevel string
|
||||
var invitationBasis, viewBasis string
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT policy_version_id, verification_level, verification_basis
|
||||
FROM company_invitation_quota_usage WHERE organization_id = $1
|
||||
ORDER BY reserved_at LIMIT 1`, organizationID).Scan(&invitationPolicy, &invitationLevel, &invitationBasis); err != nil {
|
||||
t.Fatalf("read invitation quota evidence: %v", err)
|
||||
}
|
||||
if err := fixture.pool.QueryRow(fixture.ctx, `
|
||||
SELECT policy_version_id, verification_level, verification_basis
|
||||
FROM company_card_view_quota_usage WHERE organization_id = $1
|
||||
ORDER BY last_seen_at LIMIT 1`, organizationID).Scan(&viewPolicy, &viewLevel, &viewBasis); err != nil {
|
||||
t.Fatalf("read card-view quota evidence: %v", err)
|
||||
}
|
||||
if invitationPolicy != fixture.version.ID().UUID() || viewPolicy != fixture.version.ID().UUID() ||
|
||||
invitationLevel != string(level) || viewLevel != string(level) ||
|
||||
invitationBasis != string(basis) || viewBasis != string(basis) {
|
||||
t.Fatalf("stored quota evidence = invitation %s/%s/%s view %s/%s/%s, want policy %s and %s/%s",
|
||||
invitationPolicy, invitationLevel, invitationBasis, viewPolicy, viewLevel, viewBasis, fixture.version.ID(), level, basis)
|
||||
}
|
||||
}
|
||||
@@ -39,12 +39,16 @@ var (
|
||||
// organizationTables are emptied together: memberships reference both
|
||||
// users and organizations. Creation snapshots reference idempotency records.
|
||||
organizationTables = []pgx.Identifier{
|
||||
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
|
||||
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
|
||||
}
|
||||
candidateQuestionnaireTables = []pgx.Identifier{
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
// 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, candidatePrivacyTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
@@ -242,7 +242,9 @@ 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`},
|
||||
{name: "truncate", sql: `TRUNCATE policy_versions`},
|
||||
// Include referencing quota 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`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"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/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
profileusecase "lincodex/backend/internal/usecase/profile"
|
||||
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
|
||||
)
|
||||
|
||||
const candidateQuestionnaireHTTPTimeout = 6 * time.Minute
|
||||
|
||||
func TestCandidateQuestionnaireOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidateQuestionnaireHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
|
||||
initialCatalog := questionnaireCatalogHTTP(t, harness)
|
||||
assertCatalogAvailability(t, initialCatalog, "backend", "in_development", nil, nil)
|
||||
bankFixture := seedQuestionnaireCatalogBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
now := harness.clock.Now()
|
||||
candidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-owner@example.test", passwordHash, true)
|
||||
otherCandidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-other@example.test", passwordHash, true)
|
||||
employer := createQuestionnaireHTTPEmployer(ctx, t, harness, "questionnaire-employer@example.test", passwordHash, now)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate questionnaire onboarding step: %v", err)
|
||||
}
|
||||
candidateLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.201:1234")
|
||||
otherLogin := loginCandidateQuestionnaireHTTP(t, harness, otherCandidate.Email.Address(), "192.0.2.202:1234")
|
||||
employerLogin := loginCandidateQuestionnaireHTTP(t, harness, employer.Email.Address(), "192.0.2.203:1234")
|
||||
|
||||
publicCatalogResponse := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.204:1234")
|
||||
if publicCatalogResponse.Code != http.StatusOK {
|
||||
t.Fatalf("public catalog without a session = %d %s, want 200", publicCatalogResponse.Code, publicCatalogResponse.Body.String())
|
||||
}
|
||||
currentCatalog := decodeSpecializationCatalog(t, publicCatalogResponse.Body.Bytes())
|
||||
assertCatalogAvailability(t, currentCatalog, "backend", "available", []string{"junior"}, []string{"go"})
|
||||
|
||||
guestRead := harness.request(t, http.MethodGet, "/api/v1/me/questionnaire", "", sessionHTTPTestOrigin, "", "", "192.0.2.205:1234")
|
||||
requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
initial := questionnaireHTTPRequest(t, harness, http.MethodGet, "", candidateLogin.cookie, "", "192.0.2.206:1234")
|
||||
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("empty questionnaire = %d Cache-Control=%q: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
|
||||
}
|
||||
var empty questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(initial.Body.Bytes(), &empty); err != nil {
|
||||
t.Fatalf("decode empty questionnaire: %v", err)
|
||||
}
|
||||
if empty.Version != 0 || len(empty.Specializations) != 0 || string(empty.WorkContext) != "null" || string(empty.UpdatedAt) != "null" {
|
||||
t.Fatalf("empty questionnaire = %+v, want version zero with null context and time", empty)
|
||||
}
|
||||
|
||||
firstSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.207:1234")
|
||||
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("save questionnaire = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
|
||||
}
|
||||
var saved questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
|
||||
t.Fatalf("decode saved questionnaire: %v", err)
|
||||
}
|
||||
if saved.Version != 1 || len(saved.Specializations) != 1 || saved.Specializations[0].SelfAssessedGrade != "junior" ||
|
||||
len(saved.Specializations[0].TaskLanguages) != 1 || saved.Specializations[0].TaskLanguages[0] != "go" ||
|
||||
saved.Specializations[0].Experience == nil || saved.Specializations[0].Experience.CommercialMonths != 18 ||
|
||||
saved.Specializations[0].Experience.AcademicMonths != 6 || len(saved.Specializations[0].Stack) != 1 || saved.Specializations[0].Stack[0] != "PostgreSQL" {
|
||||
t.Fatalf("saved questionnaire = %+v, want backend/junior/go version 1", saved)
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
|
||||
assertQuestionnaireExperienceConstraint(t, ctx, harness, otherCandidate.ID)
|
||||
|
||||
staleWrite := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"gRPC"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.208:1234")
|
||||
requireSessionProblem(t, staleWrite, http.StatusPreconditionFailed, "version_conflict")
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
noOp := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.209:1234")
|
||||
if noOp.Code != http.StatusOK {
|
||||
t.Fatalf("stale identical questionnaire retry = %d %s, want 200", noOp.Code, noOp.Body.String())
|
||||
}
|
||||
var noOpResponse questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(noOp.Body.Bytes(), &noOpResponse); err != nil || noOpResponse.Version != 1 {
|
||||
t.Fatalf("stale identical retry response = %+v, decode error %v; want version 1", noOpResponse, err)
|
||||
}
|
||||
|
||||
badLanguage := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"python"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.210:1234")
|
||||
if badLanguage.Code != http.StatusBadRequest || !strings.Contains(badLanguage.Body.String(), "/specializations/0/task_languages/0") {
|
||||
t.Fatalf("unoffered task language = %d %s, want field validation", badLanguage.Code, badLanguage.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
forbiddenFieldBody := questionnaireUpdateWithUnknownField(t,
|
||||
questionnaireUpdateBody(t, 1, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
"confirmed_grade", "senior")
|
||||
forbiddenField := questionnaireHTTPRequest(t, harness, http.MethodPut, forbiddenFieldBody,
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.211:1234")
|
||||
if forbiddenField.Code != http.StatusBadRequest {
|
||||
t.Fatalf("questionnaire update with confirmed_grade = %d %s, want 400", forbiddenField.Code, forbiddenField.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6)
|
||||
|
||||
otherRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", otherLogin.cookie, "", "192.0.2.212:1234")
|
||||
var other questionnaireHTTPResponse
|
||||
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &other) != nil || other.Version != 0 || len(other.Specializations) != 0 {
|
||||
t.Fatalf("other candidate questionnaire = %d %s, want private version-0 questionnaire", otherRead.Code, otherRead.Body.String())
|
||||
}
|
||||
otherDevelopmentSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 0, "ds_ml", "junior", nil, []string{"Python"}, 0, 0),
|
||||
otherLogin.cookie, otherLogin.csrf, "192.0.2.213:1234")
|
||||
if otherDevelopmentSave.Code != http.StatusOK {
|
||||
t.Fatalf("save a specialization with no available bank and no task language = %d %s, want 200", otherDevelopmentSave.Code, otherDevelopmentSave.Body.String())
|
||||
}
|
||||
|
||||
employerRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", employerLogin.cookie, "", "192.0.2.214:1234")
|
||||
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
|
||||
|
||||
// A self-assessed Senior grade remains a private claim. It cannot create a
|
||||
// confirmed category or a profile claim by itself.
|
||||
seniorSave := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.215:1234")
|
||||
if seniorSave.Code != http.StatusOK {
|
||||
t.Fatalf("save Senior self-assessment = %d %s, want 200", seniorSave.Code, seniorSave.Body.String())
|
||||
}
|
||||
var senior questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(seniorSave.Body.Bytes(), &senior); err != nil || senior.Version != 2 || senior.Specializations[0].SelfAssessedGrade != "senior" {
|
||||
t.Fatalf("Senior questionnaire = %+v, decode error %v", senior, err)
|
||||
}
|
||||
profileRead := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", sessionHTTPTestOrigin,
|
||||
candidateLogin.cookie, "", "192.0.2.216:1234")
|
||||
var profile struct {
|
||||
Version int64 `json:"version"`
|
||||
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
|
||||
}
|
||||
if profileRead.Code != http.StatusOK || json.Unmarshal(profileRead.Body.Bytes(), &profile) != nil ||
|
||||
profile.Version != 0 || len(profile.ConfirmedCategories) != 0 {
|
||||
t.Fatalf("profile after a Senior self-assessment = %d %s, want no confirmed category", profileRead.Code, profileRead.Body.String())
|
||||
}
|
||||
|
||||
// A later onboarding step never moves backwards on an identical retry.
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'completed' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("move candidate to completed onboarding: %v", err)
|
||||
}
|
||||
if response := questionnaireHTTPRequest(t, harness, http.MethodPut,
|
||||
questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6),
|
||||
candidateLogin.cookie, candidateLogin.csrf, "192.0.2.217:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("questionnaire retry after onboarding completion = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "completed")
|
||||
|
||||
// Two different changes from the same version race; exactly one wins and
|
||||
// the stale writer leaves the winner's whole body intact.
|
||||
firstConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"gRPC"}, 18, 6)
|
||||
secondConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"Redis"}, 18, 6)
|
||||
concurrentResponses := make([]*httptest.ResponseRecorder, 2)
|
||||
start := make(chan struct{})
|
||||
var wait sync.WaitGroup
|
||||
for index, body := range []string{firstConcurrent, secondConcurrent} {
|
||||
wait.Add(1)
|
||||
go func(index int, body string) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
concurrentResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, body,
|
||||
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 218+index))
|
||||
}(index, body)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
accepted, conflicted := 0, 0
|
||||
for _, response := range concurrentResponses {
|
||||
switch response.Code {
|
||||
case http.StatusOK:
|
||||
accepted++
|
||||
case http.StatusPreconditionFailed:
|
||||
conflicted++
|
||||
default:
|
||||
t.Fatalf("concurrent questionnaire save = %d %s, want 200 or 412", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if accepted != 1 || conflicted != 1 {
|
||||
t.Fatalf("concurrent questionnaire results = %d accepted, %d conflicted; want one each", accepted, conflicted)
|
||||
}
|
||||
var storedVersion int64
|
||||
var storedStack string
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, specialization.stack[1]
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
|
||||
t.Fatalf("read concurrent questionnaire winner: %v", err)
|
||||
}
|
||||
if storedVersion != 3 || (storedStack != "gRPC" && storedStack != "Redis") {
|
||||
t.Fatalf("concurrent stored questionnaire = version %d stack %q, want version 3 and one complete winner", storedVersion, storedStack)
|
||||
}
|
||||
|
||||
// Simultaneous identical saves return the one committed winner to both
|
||||
// callers without creating a second version or replacing its answer rows.
|
||||
identicalBody := questionnaireUpdateBody(t, 3, "backend", "senior", []string{"go"}, []string{"Fargate"}, 18, 6)
|
||||
identicalResponses := make([]*httptest.ResponseRecorder, 2)
|
||||
start = make(chan struct{})
|
||||
for index := range identicalResponses {
|
||||
wait.Add(1)
|
||||
go func(index int) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
identicalResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, identicalBody,
|
||||
candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 223+index))
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
for _, response := range identicalResponses {
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("concurrent identical questionnaire save = %d %s, want 200", response.Code, response.Body.String())
|
||||
}
|
||||
var result questionnaireHTTPResponse
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Version != 4 ||
|
||||
len(result.Specializations) != 1 || result.Specializations[0].Stack[0] != "Fargate" {
|
||||
t.Fatalf("concurrent identical save response = %+v, decode error %v; want same version-4 winner", result, err)
|
||||
}
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, specialization.stack[1]
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS specialization USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil {
|
||||
t.Fatalf("read identical questionnaire winner: %v", err)
|
||||
}
|
||||
if storedVersion != 4 || storedStack != "Fargate" {
|
||||
t.Fatalf("identical concurrent stored questionnaire = version %d stack %q, want version 4 and Fargate", storedVersion, storedStack)
|
||||
}
|
||||
|
||||
secondLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.220:1234")
|
||||
harness.pool.Close()
|
||||
harness = newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv)
|
||||
bankFixture.bank = assessment.NewBank(postgresadapter.NewTransactor(harness.pool))
|
||||
bankFixture.publisher = policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
||||
restartedRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.221:1234")
|
||||
var restarted questionnaireHTTPResponse
|
||||
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
|
||||
restarted.Version != 4 || len(restarted.Specializations) != 1 || restarted.Specializations[0].SelfAssessedGrade != "senior" ||
|
||||
restarted.Specializations[0].Stack[0] != storedStack {
|
||||
t.Fatalf("questionnaire after re-login and handler restart = %d %s, want version 4 and persisted winner", restartedRead.Code, restartedRead.Body.String())
|
||||
}
|
||||
assertQuestionnaireRows(t, ctx, harness, candidate.ID, 4, "backend", "senior", "go", storedStack, 18, 6)
|
||||
|
||||
// A new policy version makes the old opening ineligible for the public
|
||||
// catalog. Reopening under that policy restores availability only while the
|
||||
// pinned published-family manifest still meets its recorded threshold.
|
||||
policyVersion, err := bankFixture.publisher.Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
|
||||
Author: policyTestAuthor, Policy: integrationPolicy(11),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Publish(replacement catalog policy) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
|
||||
if _, err := bankFixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
|
||||
CatalogMetadata: &bankFixture.metadata,
|
||||
}); err != nil {
|
||||
t.Fatalf("OpenCategory(replacement catalog policy) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "available", []string{"junior"}, []string{"go"})
|
||||
if _, err := bankFixture.bank.RetireFamily(ctx, bankFixture.firstFamilyKey, 1, fixturePublisher); err != nil {
|
||||
t.Fatalf("RetireFamily(under-covered catalog) error = %v", err)
|
||||
}
|
||||
assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil)
|
||||
questionnaireAfterBankChange := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.222:1234")
|
||||
var preserved questionnaireHTTPResponse
|
||||
if questionnaireAfterBankChange.Code != http.StatusOK || json.Unmarshal(questionnaireAfterBankChange.Body.Bytes(), &preserved) != nil ||
|
||||
preserved.Version != 4 || len(preserved.Specializations) != 1 || preserved.Specializations[0].Stack[0] != storedStack {
|
||||
t.Fatalf("questionnaire after bank coverage change = %d %s, want persisted version 4", questionnaireAfterBankChange.Code, questionnaireAfterBankChange.Body.String())
|
||||
}
|
||||
|
||||
for _, privateValue := range []string{
|
||||
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
|
||||
"PostgreSQL", "gRPC", "Redis",
|
||||
} {
|
||||
if strings.Contains(harness.logs.String(), privateValue) {
|
||||
t.Fatalf("questionnaire HTTP logs contain private value %q", privateValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type questionnaireHTTPResponse struct {
|
||||
Version int64 `json:"version"`
|
||||
Specializations []questionnaireHTTPSpecialization `json:"specializations"`
|
||||
WorkContext json.RawMessage `json:"work_context"`
|
||||
UpdatedAt json.RawMessage `json:"updated_at"`
|
||||
}
|
||||
|
||||
type questionnaireHTTPSpecialization struct {
|
||||
Specialization string `json:"specialization"`
|
||||
SelfAssessedGrade string `json:"self_assessed_grade"`
|
||||
TaskLanguages []string `json:"task_languages"`
|
||||
Stack []string `json:"stack"`
|
||||
Experience *struct {
|
||||
CommercialMonths int32 `json:"commercial_months"`
|
||||
AcademicMonths int32 `json:"academic_months"`
|
||||
} `json:"experience"`
|
||||
}
|
||||
|
||||
type questionnaireCatalogResponse struct {
|
||||
Directions []struct {
|
||||
Code string `json:"code"`
|
||||
Specializations []struct {
|
||||
Code string `json:"code"`
|
||||
TestAvailability struct {
|
||||
Status string `json:"status"`
|
||||
Grades []string `json:"grades"`
|
||||
TaskLanguages []string `json:"task_languages"`
|
||||
Note *string `json:"note"`
|
||||
} `json:"test_availability"`
|
||||
} `json:"specializations"`
|
||||
} `json:"directions"`
|
||||
}
|
||||
|
||||
type questionnaireLogin struct {
|
||||
cookie string
|
||||
csrf string
|
||||
}
|
||||
|
||||
type questionnaireBankFixture struct {
|
||||
bank *assessment.Bank
|
||||
publisher *policy.Publisher
|
||||
metadata domain.AssessmentCategoryCatalogMetadata
|
||||
firstFamilyKey domain.AssessmentFamilyKey
|
||||
}
|
||||
|
||||
func seedQuestionnaireCatalogBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) questionnaireBankFixture {
|
||||
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),
|
||||
}
|
||||
if _, err := bank.ImportBundle(ctx, fixture.demoBundle); err != nil {
|
||||
t.Fatalf("ImportBundle(unreviewed base bundle) error = %v", err)
|
||||
}
|
||||
unreviewedAvailability, err := bank.SpecializationAvailability(ctx)
|
||||
if err != nil || len(unreviewedAvailability) != 0 {
|
||||
t.Fatalf("catalog availability after importing an unreviewed draft = %v, %v; want no rows", unreviewedAvailability, err)
|
||||
}
|
||||
policyVersion, err := publisher.Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
|
||||
Author: policyTestAuthor, Policy: integrationPolicy(11),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Publish(questionnaire grading policy) error = %v", err)
|
||||
}
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
reviewed := fixture.reviewedBundle(int(required))
|
||||
if _, err := bank.ImportBundle(ctx, reviewed); err != nil {
|
||||
t.Fatalf("ImportBundle(reviewed questionnaire fixture) error = %v", err)
|
||||
}
|
||||
for _, family := range reviewed.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)
|
||||
}
|
||||
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener,
|
||||
CatalogMetadata: &metadata,
|
||||
}); err != nil {
|
||||
t.Fatalf("OpenCategory(reviewed questionnaire fixture) error = %v", err)
|
||||
}
|
||||
return questionnaireBankFixture{
|
||||
bank: bank, publisher: publisher, metadata: metadata,
|
||||
firstFamilyKey: domain.AssessmentFamilyKey(reviewed.Families[0].Key),
|
||||
}
|
||||
}
|
||||
|
||||
func newCandidateQuestionnaireHTTPHarness(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)}
|
||||
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)
|
||||
}
|
||||
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))
|
||||
profileHandler := v1.NewProfileHandler(profileusecase.NewService(transactor, clock.Now))
|
||||
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
|
||||
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
|
||||
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
|
||||
prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
|
||||
}
|
||||
|
||||
func createQuestionnaireHTTPEmployer(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
registeredAt time.Time,
|
||||
) 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: 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)
|
||||
}
|
||||
verified, 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 verified
|
||||
}
|
||||
|
||||
func loginCandidateQuestionnaireHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) questionnaireLogin {
|
||||
t.Helper()
|
||||
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("login questionnaire account = %d %s", 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 questionnaire login response: %v", err)
|
||||
}
|
||||
return questionnaireLogin{cookie: cookie.Value, csrf: body.CSRFToken}
|
||||
}
|
||||
|
||||
func questionnaireHTTPRequest(
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
method, body, cookie, csrf, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return harness.request(t, method, "/api/v1/me/questionnaire", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
|
||||
}
|
||||
|
||||
func questionnaireUpdateBody(
|
||||
t *testing.T,
|
||||
version int64,
|
||||
specialization, grade string,
|
||||
languages, stack []string,
|
||||
commercialMonths, academicMonths int,
|
||||
) string {
|
||||
t.Helper()
|
||||
if languages == nil {
|
||||
languages = []string{}
|
||||
}
|
||||
if stack == nil {
|
||||
stack = []string{}
|
||||
}
|
||||
var experience any
|
||||
if commercialMonths != 0 || academicMonths != 0 {
|
||||
experience = map[string]any{"commercial_months": commercialMonths, "academic_months": academicMonths}
|
||||
}
|
||||
encoded, err := json.Marshal(map[string]any{
|
||||
"expected_version": version,
|
||||
"specializations": []any{map[string]any{
|
||||
"specialization": specialization, "self_assessed_grade": grade,
|
||||
"task_languages": languages, "stack": stack, "experience": experience,
|
||||
}},
|
||||
"work_context": map[string]any{"work_formats": []string{"remote"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal questionnaire request: %v", err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func questionnaireUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal([]byte(requestBody), &body); err != nil {
|
||||
t.Fatalf("decode questionnaire request fixture: %v", err)
|
||||
}
|
||||
body[field] = value
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal questionnaire request with %s: %v", field, err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func questionnaireCatalogHTTP(t *testing.T, harness *sessionHTTPHarness) questionnaireCatalogResponse {
|
||||
t.Helper()
|
||||
response := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.200:1234")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GetSpecializationCatalog() = %d %s, want 200", response.Code, response.Body.String())
|
||||
}
|
||||
return decodeSpecializationCatalog(t, response.Body.Bytes())
|
||||
}
|
||||
|
||||
func decodeSpecializationCatalog(t *testing.T, encoded []byte) questionnaireCatalogResponse {
|
||||
t.Helper()
|
||||
var catalog questionnaireCatalogResponse
|
||||
if err := json.Unmarshal(encoded, &catalog); err != nil {
|
||||
t.Fatalf("decode specialization catalog: %v", err)
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
|
||||
func assertCatalogAvailability(t *testing.T, catalog questionnaireCatalogResponse, code, status string, grades, languages []string) {
|
||||
t.Helper()
|
||||
for _, direction := range catalog.Directions {
|
||||
for _, specialization := range direction.Specializations {
|
||||
if specialization.Code != code {
|
||||
continue
|
||||
}
|
||||
actual := specialization.TestAvailability
|
||||
if actual.Status != status || !slices.Equal(actual.Grades, grades) || !slices.Equal(actual.TaskLanguages, languages) {
|
||||
t.Fatalf("catalog availability for %s = %+v; want %s grades=%v languages=%v", code, actual, status, grades, languages)
|
||||
}
|
||||
if status == "in_development" && (actual.Note == nil || *actual.Note != "Тест в разработке.") {
|
||||
t.Fatalf("catalog development note for %s = %v, want fixed note", code, actual.Note)
|
||||
}
|
||||
if status == "available" && actual.Note != nil {
|
||||
t.Fatalf("catalog availability note for %s = %q, want null", code, *actual.Note)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("catalog is missing specialization %s", code)
|
||||
}
|
||||
|
||||
func assertQuestionnaireRows(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *sessionHTTPHarness,
|
||||
userID uuid.UUID,
|
||||
wantVersion int64,
|
||||
specialization, grade, language, stack string,
|
||||
commercialMonths, academicMonths int32,
|
||||
) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_questionnaires WHERE user_id = $1", userID).Scan(&count); err != nil {
|
||||
t.Fatalf("count questionnaire rows: %v", err)
|
||||
}
|
||||
wantRows := 1
|
||||
if wantVersion == 0 {
|
||||
wantRows = 0
|
||||
}
|
||||
if count != wantRows {
|
||||
t.Fatalf("questionnaire rows = %d, want %d", count, wantRows)
|
||||
}
|
||||
if wantVersion == 0 {
|
||||
return
|
||||
}
|
||||
var version int64
|
||||
var storedSpecialization, storedGrade, storedLanguage, storedStack string
|
||||
var storedCommercial, storedAcademic int32
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT questionnaire.version, answer.specialization, answer.self_assessed_grade,
|
||||
answer.task_languages[1], answer.stack[1], answer.commercial_months, answer.academic_months
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
JOIN candidate_questionnaire_specializations AS answer USING (user_id)
|
||||
WHERE questionnaire.user_id = $1`, userID).Scan(
|
||||
&version, &storedSpecialization, &storedGrade, &storedLanguage, &storedStack, &storedCommercial, &storedAcademic,
|
||||
); err != nil {
|
||||
t.Fatalf("read stored questionnaire: %v", err)
|
||||
}
|
||||
if version != wantVersion || storedSpecialization != specialization || storedGrade != grade || storedLanguage != language ||
|
||||
storedStack != stack || storedCommercial != commercialMonths || storedAcademic != academicMonths {
|
||||
t.Fatalf("stored questionnaire = version %d %s/%s/%s/%s/%d/%d; want %d %s/%s/%s/%s/%d/%d",
|
||||
version, storedSpecialization, storedGrade, storedLanguage, storedStack, storedCommercial, storedAcademic,
|
||||
wantVersion, specialization, grade, language, stack, commercialMonths, academicMonths)
|
||||
}
|
||||
}
|
||||
|
||||
func assertQuestionnaireOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) {
|
||||
t.Helper()
|
||||
var step string
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil {
|
||||
t.Fatalf("read questionnaire onboarding step: %v", err)
|
||||
}
|
||||
if step != want {
|
||||
t.Fatalf("questionnaire onboarding step = %q, want %q", step, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertQuestionnaireExperienceConstraint(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
|
||||
t.Helper()
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin questionnaire constraint check: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
t.Errorf("rollback questionnaire constraint check: %v", err)
|
||||
}
|
||||
}()
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO candidate_questionnaires (user_id, version, work_formats, created_at, updated_at)
|
||||
VALUES ($1, 1, ARRAY['remote']::text[], statement_timestamp(), statement_timestamp())`, userID); err != nil {
|
||||
t.Fatalf("insert empty questionnaire row for DB constraint check: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO candidate_questionnaire_specializations
|
||||
(user_id, ordinal, specialization, self_assessed_grade, task_languages, stack, commercial_months, academic_months)
|
||||
VALUES ($1, 0, 'backend', 'junior', ARRAY[]::text[], ARRAY[]::text[], 18, NULL)`, userID)
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != "candidate_questionnaire_specializations_experience" {
|
||||
t.Fatalf("one-sided experience month value error = %v, want experience CHECK", err)
|
||||
}
|
||||
}
|
||||
@@ -16292,9 +16292,9 @@ func (s *NumberItemContentFormat) UnmarshalText(data []byte) error {
|
||||
// - candidate_profile: candidate profile.
|
||||
// - candidate_questionnaire: candidate questionnaire.
|
||||
// - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in
|
||||
// the questionnaire, and this step offers it first; only an assessment result confirms a grade. The
|
||||
// first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step
|
||||
// (planned).
|
||||
// the questionnaire, and this step offers it first; only an assessment result confirms a grade. A
|
||||
// successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step and
|
||||
// leaves every other saved step unchanged.
|
||||
// - employer_company: company profile of the employer.
|
||||
// - completed: onboarding is finished; the client opens the scenario home.
|
||||
//
|
||||
|
||||
@@ -17,12 +17,14 @@ import (
|
||||
type Handler struct {
|
||||
api.UnimplementedHandler
|
||||
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
organization *OrganizationHandler
|
||||
problems *problem.Responder
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
questionnaire *QuestionnaireHandler
|
||||
catalog *CatalogHandler
|
||||
organization *OrganizationHandler
|
||||
problems *problem.Responder
|
||||
}
|
||||
|
||||
var _ api.Handler = (*Handler)(nil)
|
||||
@@ -45,6 +47,16 @@ func WithProfile(profile *ProfileHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.profile = profile }
|
||||
}
|
||||
|
||||
// WithQuestionnaire serves the candidate's questionnaire and self-assessment.
|
||||
func WithQuestionnaire(questionnaire *QuestionnaireHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.questionnaire = questionnaire }
|
||||
}
|
||||
|
||||
// WithCatalog serves the public specialization catalog and bank availability.
|
||||
func WithCatalog(catalog *CatalogHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.catalog = catalog }
|
||||
}
|
||||
|
||||
// WithOrganization serves company profiles and owner operations.
|
||||
func WithOrganization(organization *OrganizationHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.organization = organization }
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
// CatalogOperations reads current assessment availability for the public
|
||||
// specialization catalog.
|
||||
type CatalogOperations interface {
|
||||
SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error)
|
||||
}
|
||||
|
||||
// CatalogHandler serves the public, non-personal specialization catalog.
|
||||
type CatalogHandler struct {
|
||||
operations CatalogOperations
|
||||
}
|
||||
|
||||
func NewCatalogHandler(operations CatalogOperations) *CatalogHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewCatalogHandler - catalog operations must not be nil")
|
||||
}
|
||||
return &CatalogHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) GetSpecializationCatalog(ctx context.Context) (*api.SpecializationCatalog, error) {
|
||||
if handler.catalog == nil {
|
||||
return handler.UnimplementedHandler.GetSpecializationCatalog(ctx)
|
||||
}
|
||||
return handler.catalog.GetSpecializationCatalog(ctx)
|
||||
}
|
||||
|
||||
func (handler *CatalogHandler) GetSpecializationCatalog(ctx context.Context) (*api.SpecializationCatalog, error) {
|
||||
availability, err := handler.operations.SpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CatalogHandler.GetSpecializationCatalog - read availability: %w", err)
|
||||
}
|
||||
catalog, err := buildSpecializationCatalog(availability)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CatalogHandler.GetSpecializationCatalog - build catalog: %w", err)
|
||||
}
|
||||
return catalog, nil
|
||||
}
|
||||
|
||||
type catalogSpecializationDefinition struct {
|
||||
code domain.SpecializationCode
|
||||
title string
|
||||
}
|
||||
|
||||
type catalogDirectionDefinition struct {
|
||||
code api.DirectionCode
|
||||
title string
|
||||
specializations []catalogSpecializationDefinition
|
||||
}
|
||||
|
||||
var catalogDirectionDefinitions = []catalogDirectionDefinition{
|
||||
{
|
||||
code: api.DirectionCodeDevelopment, title: "Разработка",
|
||||
specializations: []catalogSpecializationDefinition{
|
||||
{code: domain.SpecializationBackend, title: "Backend"},
|
||||
{code: domain.SpecializationFrontend, title: "Frontend"},
|
||||
{code: domain.SpecializationMobile, title: "Mobile"},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: api.DirectionCodeInfrastructure, title: "Инфраструктура",
|
||||
specializations: []catalogSpecializationDefinition{
|
||||
{code: domain.SpecializationNetworkEngineer, title: "Сетевой инженер"},
|
||||
{code: domain.SpecializationDevopsSRE, title: "DevOps/SRE"},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: api.DirectionCodeData, title: "Данные",
|
||||
specializations: []catalogSpecializationDefinition{
|
||||
{code: domain.SpecializationDataAnalyst, title: "Аналитик данных"},
|
||||
{code: domain.SpecializationDSML, title: "DS/ML"},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: api.DirectionCodeSecurity, title: "Безопасность",
|
||||
specializations: []catalogSpecializationDefinition{
|
||||
{code: domain.SpecializationInformationSecurity, title: "Информационная безопасность"},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: api.DirectionCodeQuality, title: "Качество",
|
||||
specializations: []catalogSpecializationDefinition{
|
||||
{code: domain.SpecializationQA, title: "QA"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var catalogGradeDefinitions = []api.CatalogGrade{
|
||||
{Code: api.GradeCodeIntern, Title: "Стажер"},
|
||||
{Code: api.GradeCodeJunior, Title: "Junior"},
|
||||
{Code: api.GradeCodeMiddle, Title: "Middle"},
|
||||
{Code: api.GradeCodeSenior, Title: "Senior"},
|
||||
}
|
||||
|
||||
func buildSpecializationCatalog(availability []domain.SpecializationAvailability) (*api.SpecializationCatalog, error) {
|
||||
bySpecialization := make(map[domain.SpecializationCode]domain.SpecializationAvailability, len(availability))
|
||||
for _, item := range availability {
|
||||
if !item.Specialization.IsKnown() {
|
||||
return nil, fmt.Errorf("buildSpecializationCatalog - availability has an unknown specialization")
|
||||
}
|
||||
if _, exists := bySpecialization[item.Specialization]; exists {
|
||||
return nil, fmt.Errorf("buildSpecializationCatalog - availability repeats a specialization")
|
||||
}
|
||||
if err := validateCatalogAvailability(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bySpecialization[item.Specialization] = item
|
||||
}
|
||||
|
||||
directions := make([]api.CatalogDirection, 0, len(catalogDirectionDefinitions))
|
||||
for _, definition := range catalogDirectionDefinitions {
|
||||
items := make([]api.CatalogSpecialization, 0, len(definition.specializations))
|
||||
for _, specialization := range definition.specializations {
|
||||
items = append(items, catalogSpecializationResponse(specialization, bySpecialization[specialization.code]))
|
||||
}
|
||||
directions = append(directions, api.CatalogDirection{
|
||||
Code: definition.code, Title: definition.title, Specializations: items,
|
||||
})
|
||||
}
|
||||
return &api.SpecializationCatalog{Directions: directions, Grades: slices.Clone(catalogGradeDefinitions)}, nil
|
||||
}
|
||||
|
||||
func validateCatalogAvailability(item domain.SpecializationAvailability) error {
|
||||
if len(item.Grades) == 0 && len(item.TaskLanguages) > 0 {
|
||||
return fmt.Errorf("validateCatalogAvailability - unavailable specialization has task languages")
|
||||
}
|
||||
seenGrades := make(map[domain.GradeCode]struct{}, len(item.Grades))
|
||||
for _, grade := range item.Grades {
|
||||
if !grade.IsKnown() {
|
||||
return fmt.Errorf("validateCatalogAvailability - availability has an unknown grade")
|
||||
}
|
||||
if _, exists := seenGrades[grade]; exists {
|
||||
return fmt.Errorf("validateCatalogAvailability - availability repeats a grade")
|
||||
}
|
||||
seenGrades[grade] = struct{}{}
|
||||
}
|
||||
seenLanguages := make(map[domain.TaskLanguageCode]struct{}, len(item.TaskLanguages))
|
||||
for _, language := range item.TaskLanguages {
|
||||
if !language.IsKnown() {
|
||||
return fmt.Errorf("validateCatalogAvailability - availability has an unknown task language")
|
||||
}
|
||||
if _, exists := seenLanguages[language]; exists {
|
||||
return fmt.Errorf("validateCatalogAvailability - availability repeats a task language")
|
||||
}
|
||||
seenLanguages[language] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func catalogSpecializationResponse(
|
||||
definition catalogSpecializationDefinition,
|
||||
availability domain.SpecializationAvailability,
|
||||
) api.CatalogSpecialization {
|
||||
grades := make([]api.GradeCode, 0, len(availability.Grades))
|
||||
for _, grade := range availability.Grades {
|
||||
grades = append(grades, api.GradeCode(grade))
|
||||
}
|
||||
languages := make([]api.TaskLanguage, 0, len(availability.TaskLanguages))
|
||||
for _, language := range availability.TaskLanguages {
|
||||
languages = append(languages, api.TaskLanguage(language))
|
||||
}
|
||||
status := api.TestAvailabilityStatusInDevelopment
|
||||
note := api.NewNilString("Тест в разработке.")
|
||||
if len(grades) > 0 {
|
||||
status = api.TestAvailabilityStatusAvailable
|
||||
note.SetToNull()
|
||||
}
|
||||
return api.CatalogSpecialization{
|
||||
Code: api.SpecializationCode(definition.code), Title: definition.title,
|
||||
TestAvailability: api.TestAvailability{
|
||||
Status: status, Grades: grades, TaskLanguages: languages, Note: note,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
type catalogTestOperations struct {
|
||||
availability []domain.SpecializationAvailability
|
||||
err error
|
||||
}
|
||||
|
||||
func (operations catalogTestOperations) SpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
return operations.availability, operations.err
|
||||
}
|
||||
|
||||
func TestCatalogHandlerBuildsStaticCatalogFromCurrentBankAvailability(t *testing.T) {
|
||||
handler := NewCatalogHandler(catalogTestOperations{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
Grades: []domain.GradeCode{domain.GradeJunior, domain.GradeSenior},
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}}})
|
||||
catalog, err := handler.GetSpecializationCatalog(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("GetSpecializationCatalog() error = %v", err)
|
||||
}
|
||||
if len(catalog.Directions) != 5 || len(catalog.Grades) != 4 {
|
||||
t.Fatalf("catalog has %d directions and %d grades, want 5 and 4", len(catalog.Directions), len(catalog.Grades))
|
||||
}
|
||||
backend := catalog.Directions[0].Specializations[0]
|
||||
if backend.Code != api.SpecializationCodeBackend || backend.TestAvailability.Status != api.TestAvailabilityStatusAvailable ||
|
||||
len(backend.TestAvailability.Grades) != 2 || backend.TestAvailability.Grades[0] != api.GradeCodeJunior ||
|
||||
len(backend.TestAvailability.TaskLanguages) != 1 || backend.TestAvailability.TaskLanguages[0] != api.TaskLanguageGo ||
|
||||
!backend.TestAvailability.Note.IsNull() {
|
||||
t.Fatalf("Backend availability = %+v, want live junior/senior Go bank", backend.TestAvailability)
|
||||
}
|
||||
dsml := catalog.Directions[2].Specializations[1]
|
||||
if dsml.Code != api.SpecializationCodeDsMl || dsml.TestAvailability.Status != api.TestAvailabilityStatusInDevelopment ||
|
||||
len(dsml.TestAvailability.Grades) != 0 || dsml.TestAvailability.Grades == nil ||
|
||||
len(dsml.TestAvailability.TaskLanguages) != 0 || dsml.TestAvailability.TaskLanguages == nil {
|
||||
t.Fatalf("DS/ML availability = %+v, want in-development with empty arrays", dsml.TestAvailability)
|
||||
}
|
||||
if note, ok := dsml.TestAvailability.Note.Get(); !ok || note != "Тест в разработке." {
|
||||
t.Fatalf("DS/ML note = %q, set %v; want fixed development note", note, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogHandlerReturnsOperationFailure(t *testing.T) {
|
||||
wantErr := errors.New("catalog unavailable")
|
||||
handler := NewCatalogHandler(catalogTestOperations{err: wantErr})
|
||||
if _, err := handler.GetSpecializationCatalog(context.Background()); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("GetSpecializationCatalog() error = %v, want wrapped operation error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSpecializationCatalogFailsClosedOnMalformedAvailability(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
availability []domain.SpecializationAvailability
|
||||
}{
|
||||
{
|
||||
name: "unknown specialization",
|
||||
availability: []domain.SpecializationAvailability{{
|
||||
Specialization: "unknown", Grades: []domain.GradeCode{domain.GradeJunior},
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "duplicate specialization",
|
||||
availability: []domain.SpecializationAvailability{
|
||||
{Specialization: domain.SpecializationBackend},
|
||||
{Specialization: domain.SpecializationBackend},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown grade",
|
||||
availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend, Grades: []domain.GradeCode{"lead"},
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "language without published grade",
|
||||
availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend, TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := buildSpecializationCatalog(test.availability); err == nil {
|
||||
t.Fatal("buildSpecializationCatalog() error = nil, want malformed availability error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
|
||||
)
|
||||
|
||||
// QuestionnaireOperations reads and version-saves the authenticated
|
||||
// candidate's private questionnaire.
|
||||
type QuestionnaireOperations interface {
|
||||
GetMyQuestionnaire(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error)
|
||||
SaveMyQuestionnaire(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateQuestionnaireInput) (domain.CandidateQuestionnaire, error)
|
||||
}
|
||||
|
||||
// QuestionnaireHandler serves a candidate's own questionnaire operations.
|
||||
type QuestionnaireHandler struct {
|
||||
operations QuestionnaireOperations
|
||||
}
|
||||
|
||||
func NewQuestionnaireHandler(operations QuestionnaireOperations) *QuestionnaireHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewQuestionnaireHandler - questionnaire operations must not be nil")
|
||||
}
|
||||
return &QuestionnaireHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyQuestionnaire(ctx context.Context) (api.GetMyQuestionnaireRes, error) {
|
||||
if handler.questionnaire == nil {
|
||||
return handler.UnimplementedHandler.GetMyQuestionnaire(ctx)
|
||||
}
|
||||
return handler.questionnaire.GetMyQuestionnaire(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) SaveMyQuestionnaire(ctx context.Context, request *api.CandidateQuestionnaireUpdate) (api.SaveMyQuestionnaireRes, error) {
|
||||
if handler.questionnaire == nil {
|
||||
return handler.UnimplementedHandler.SaveMyQuestionnaire(ctx, request)
|
||||
}
|
||||
return handler.questionnaire.SaveMyQuestionnaire(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *QuestionnaireHandler) GetMyQuestionnaire(ctx context.Context) (api.GetMyQuestionnaireRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
questionnaire, err := handler.operations.GetMyQuestionnaire(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
return questionnaireReadFailure(ctx, err)
|
||||
}
|
||||
return &api.CandidateQuestionnaireHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: candidateQuestionnaireResponse(questionnaire),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *QuestionnaireHandler) SaveMyQuestionnaire(
|
||||
ctx context.Context,
|
||||
request *api.CandidateQuestionnaireUpdate,
|
||||
) (api.SaveMyQuestionnaireRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SaveMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
questionnaire, err := handler.operations.SaveMyQuestionnaire(
|
||||
ctx, principal.UserID, int64(request.ExpectedVersion), candidateQuestionnaireInput(request),
|
||||
)
|
||||
if err != nil {
|
||||
return questionnaireSaveFailure(ctx, err)
|
||||
}
|
||||
return &api.CandidateQuestionnaireHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: candidateQuestionnaireResponse(questionnaire),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func questionnaireReadFailure(ctx context.Context, err error) (api.GetMyQuestionnaireRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, questionnaireusecase.ErrForbidden), errors.Is(err, questionnaireusecase.ErrEmailNotVerified):
|
||||
return (*api.GetMyQuestionnaireForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.GetMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func questionnaireSaveFailure(ctx context.Context, err error) (api.SaveMyQuestionnaireRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrCandidateQuestionnaireVersionConflict), errors.Is(err, outbound.ErrCandidateQuestionnaireVersionConflict):
|
||||
return (*api.SaveMyQuestionnairePreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, questionnaireusecase.ErrForbidden), errors.Is(err, questionnaireusecase.ErrEmailNotVerified):
|
||||
return (*api.SaveMyQuestionnaireForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.SaveMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
case errors.Is(err, domain.ErrInvalidCandidateQuestionnaire):
|
||||
fieldError, ok := errors.AsType[*domain.CandidateQuestionnaireFieldError](err)
|
||||
if !ok {
|
||||
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func candidateQuestionnaireInput(request *api.CandidateQuestionnaireUpdate) domain.CandidateQuestionnaireInput {
|
||||
input := domain.CandidateQuestionnaireInput{
|
||||
Specializations: make([]domain.QuestionnaireSpecialization, 0, len(request.Specializations)),
|
||||
WorkFormats: make([]domain.QuestionnaireWorkFormat, 0, len(request.WorkContext.WorkFormats)),
|
||||
}
|
||||
for _, format := range request.WorkContext.WorkFormats {
|
||||
input.WorkFormats = append(input.WorkFormats, domain.QuestionnaireWorkFormat(format))
|
||||
}
|
||||
for _, answer := range request.Specializations {
|
||||
item := domain.QuestionnaireSpecialization{
|
||||
Specialization: domain.SpecializationCode(answer.Specialization),
|
||||
SelfAssessedGrade: domain.GradeCode(answer.SelfAssessedGrade),
|
||||
TaskLanguages: make([]domain.TaskLanguageCode, 0, len(answer.TaskLanguages)),
|
||||
Stack: make([]string, 0, len(answer.Stack)),
|
||||
}
|
||||
for _, language := range answer.TaskLanguages {
|
||||
item.TaskLanguages = append(item.TaskLanguages, domain.TaskLanguageCode(language))
|
||||
}
|
||||
for _, tag := range answer.Stack {
|
||||
item.Stack = append(item.Stack, string(tag))
|
||||
}
|
||||
if experience, ok := answer.Experience.Get(); ok {
|
||||
item.Experience = &domain.QuestionnaireExperience{
|
||||
CommercialMonths: experience.CommercialMonths,
|
||||
AcademicMonths: experience.AcademicMonths,
|
||||
}
|
||||
}
|
||||
input.Specializations = append(input.Specializations, item)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
func candidateQuestionnaireResponse(questionnaire domain.CandidateQuestionnaire) api.CandidateQuestionnaire {
|
||||
answers := questionnaire.Specializations()
|
||||
response := api.CandidateQuestionnaire{
|
||||
Version: api.QuestionnaireVersion(questionnaire.Version()),
|
||||
Specializations: make([]api.QuestionnaireSpecialization, 0, len(answers)),
|
||||
}
|
||||
response.WorkContext.SetToNull()
|
||||
response.UpdatedAt.SetToNull()
|
||||
if questionnaire.Version() > 0 {
|
||||
workContext := api.WorkContext{WorkFormats: make([]api.WorkFormat, 0, len(questionnaire.WorkFormats()))}
|
||||
for _, format := range questionnaire.WorkFormats() {
|
||||
workContext.WorkFormats = append(workContext.WorkFormats, api.WorkFormat(format))
|
||||
}
|
||||
response.WorkContext.SetTo(workContext)
|
||||
response.UpdatedAt.SetTo(api.Timestamp(questionnaire.UpdatedAt()))
|
||||
}
|
||||
for _, answer := range answers {
|
||||
item := api.QuestionnaireSpecialization{
|
||||
Specialization: api.SpecializationCode(answer.Specialization),
|
||||
SelfAssessedGrade: api.GradeCode(answer.SelfAssessedGrade),
|
||||
TaskLanguages: make([]api.TaskLanguage, 0, len(answer.TaskLanguages)),
|
||||
Stack: make([]api.StackTag, 0, len(answer.Stack)),
|
||||
}
|
||||
for _, language := range answer.TaskLanguages {
|
||||
item.TaskLanguages = append(item.TaskLanguages, api.TaskLanguage(language))
|
||||
}
|
||||
for _, tag := range answer.Stack {
|
||||
item.Stack = append(item.Stack, api.StackTag(tag))
|
||||
}
|
||||
if answer.Experience == nil {
|
||||
item.Experience.SetToNull()
|
||||
} else {
|
||||
item.Experience.SetTo(api.CandidateExperience{
|
||||
CommercialMonths: answer.Experience.CommercialMonths,
|
||||
AcademicMonths: answer.Experience.AcademicMonths,
|
||||
})
|
||||
}
|
||||
response.Specializations = append(response.Specializations, item)
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const assessmentCategoryManifestDomain = "lincodex.assessment.category-manifest.v1\x00"
|
||||
|
||||
type assessmentCatalogManifestJSONEntry struct {
|
||||
FamilyKey string `json:"family_key"`
|
||||
Version int32 `json:"version"`
|
||||
ContentSHA256 string `json:"content_sha256"`
|
||||
}
|
||||
|
||||
type assessmentCatalogAggregate struct {
|
||||
grades map[domain.GradeCode]struct{}
|
||||
taskLanguages map[domain.TaskLanguageCode]struct{}
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) BindCategoryCatalog(
|
||||
ctx context.Context,
|
||||
opening domain.AssessmentCategoryOpening,
|
||||
metadata domain.AssessmentCategoryCatalogMetadata,
|
||||
) error {
|
||||
const location = "assessmentBankRepository.BindCategoryCatalog"
|
||||
if opening.ID == uuid.Nil || metadata.IsZero() {
|
||||
return fmt.Errorf("%s - opening and reviewed metadata must be set: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(opening.Category))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read published manifest: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
|
||||
if err != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
|
||||
return fmt.Errorf("%s - published manifest row is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
entries = append(entries, domain.AssessmentCategoryManifestEntry{
|
||||
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
|
||||
})
|
||||
}
|
||||
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - fingerprint published manifest: %w", location, err)
|
||||
}
|
||||
if len(entries) < int(opening.RequiredFamilies) {
|
||||
return fmt.Errorf("%s - published manifest no longer meets opening coverage: %w", location, outbound.ErrAssessmentCoverageInsufficient)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentCategoryCatalogBinding(ctx, sqlc.InsertAssessmentCategoryCatalogBindingParams{
|
||||
OpeningID: pgUUID(opening.ID), Specialization: string(metadata.Specialization()),
|
||||
Grade: string(metadata.Grade()), TaskLanguages: questionnaireTaskLanguageStrings(metadata.TaskLanguages()),
|
||||
PublishedManifestSha256: fingerprint[:], ReviewedBy: string(opening.OpenedBy),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert reviewed binding: %w", location, mapAssessmentCatalogError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ListCurrentSpecializationAvailability(
|
||||
ctx context.Context,
|
||||
) ([]domain.SpecializationAvailability, error) {
|
||||
const location = "assessmentBankRepository.ListCurrentSpecializationAvailability"
|
||||
rows, err := repository.queries.ListCurrentSpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select current bank projection: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
aggregates := make(map[domain.SpecializationCode]*assessmentCatalogAggregate)
|
||||
for _, row := range rows {
|
||||
metadata, available, err := currentAssessmentCatalogMetadata(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate current binding: %w", location, err)
|
||||
}
|
||||
if !available {
|
||||
continue
|
||||
}
|
||||
addAssessmentCatalogMetadata(aggregates, metadata)
|
||||
}
|
||||
return buildAssessmentCatalogAvailability(aggregates), nil
|
||||
}
|
||||
|
||||
func currentAssessmentCatalogMetadata(
|
||||
row sqlc.ListCurrentSpecializationAvailabilityRow,
|
||||
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
|
||||
if !row.EffectivePolicyID.Valid || row.EffectivePolicyID.Bytes != row.PolicyVersionID.Bytes ||
|
||||
row.PublishedCount < row.RequiredFamilies {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
|
||||
}
|
||||
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("decode published manifest: %w", err)
|
||||
}
|
||||
if len(entries) != int(row.PublishedCount) {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("published manifest count is inconsistent: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("fingerprint published manifest: %w", err)
|
||||
}
|
||||
if !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
|
||||
}
|
||||
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
|
||||
domain.SpecializationCode(row.Specialization), domain.GradeCode(row.Grade), questionnaireTaskLanguages(row.TaskLanguages),
|
||||
)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("restore reviewed catalog binding: %w", err)
|
||||
}
|
||||
return metadata, true, nil
|
||||
}
|
||||
|
||||
func addAssessmentCatalogMetadata(
|
||||
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
|
||||
metadata domain.AssessmentCategoryCatalogMetadata,
|
||||
) {
|
||||
aggregate := aggregates[metadata.Specialization()]
|
||||
if aggregate == nil {
|
||||
aggregate = &assessmentCatalogAggregate{
|
||||
grades: make(map[domain.GradeCode]struct{}), taskLanguages: make(map[domain.TaskLanguageCode]struct{}),
|
||||
}
|
||||
aggregates[metadata.Specialization()] = aggregate
|
||||
}
|
||||
aggregate.grades[metadata.Grade()] = struct{}{}
|
||||
for _, language := range metadata.TaskLanguages() {
|
||||
aggregate.taskLanguages[language] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func buildAssessmentCatalogAvailability(
|
||||
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
|
||||
) []domain.SpecializationAvailability {
|
||||
availability := make([]domain.SpecializationAvailability, 0, len(aggregates))
|
||||
for specialization, aggregate := range aggregates {
|
||||
grades := make([]domain.GradeCode, 0, len(aggregate.grades))
|
||||
for grade := range aggregate.grades {
|
||||
grades = append(grades, grade)
|
||||
}
|
||||
sort.Slice(grades, func(i, j int) bool {
|
||||
return questionnaireGradeRank(grades[i]) < questionnaireGradeRank(grades[j])
|
||||
})
|
||||
languages := make([]domain.TaskLanguageCode, 0, len(aggregate.taskLanguages))
|
||||
for language := range aggregate.taskLanguages {
|
||||
languages = append(languages, language)
|
||||
}
|
||||
sort.Slice(languages, func(i, j int) bool {
|
||||
return questionnaireTaskLanguageRank(languages[i]) < questionnaireTaskLanguageRank(languages[j])
|
||||
})
|
||||
availability = append(availability, domain.SpecializationAvailability{
|
||||
Specialization: specialization, Grades: grades, TaskLanguages: languages,
|
||||
})
|
||||
}
|
||||
sort.Slice(availability, func(i, j int) bool {
|
||||
return availability[i].Specialization < availability[j].Specialization
|
||||
})
|
||||
return availability
|
||||
}
|
||||
|
||||
func decodeAssessmentCategoryManifest(encoded string) ([]domain.AssessmentCategoryManifestEntry, error) {
|
||||
var rows []assessmentCatalogManifestJSONEntry
|
||||
if err := json.Unmarshal([]byte(encoded), &rows); err != nil {
|
||||
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - decode JSON: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
|
||||
if err != nil || row.Version < 1 {
|
||||
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - manifest identity is invalid: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
digest, err := hex.DecodeString(row.ContentSHA256)
|
||||
if err != nil || len(digest) != sha256.Size {
|
||||
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - content hash is invalid: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
entries = append(entries, domain.AssessmentCategoryManifestEntry{
|
||||
FamilyKey: key, Version: row.Version, ContentSHA256: digest,
|
||||
})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func assessmentCategoryManifestFingerprint(entries []domain.AssessmentCategoryManifestEntry) ([sha256.Size]byte, error) {
|
||||
const location = "postgres.assessmentCategoryManifestFingerprint"
|
||||
if len(entries) == 0 {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("%s - manifest must contain a published family: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
ordered := slices.Clone(entries)
|
||||
sort.Slice(ordered, func(i, j int) bool {
|
||||
if ordered[i].FamilyKey == ordered[j].FamilyKey {
|
||||
return ordered[i].Version < ordered[j].Version
|
||||
}
|
||||
return ordered[i].FamilyKey < ordered[j].FamilyKey
|
||||
})
|
||||
canonical := []byte(assessmentCategoryManifestDomain)
|
||||
for index, entry := range ordered {
|
||||
if entry.Version < 1 || len(entry.ContentSHA256) != sha256.Size {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("%s - entry identity or hash is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if index > 0 && ordered[index-1].FamilyKey == entry.FamilyKey {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("%s - a family appears more than once: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
key := []byte(entry.FamilyKey)
|
||||
keyLength := uint64(len(key))
|
||||
if len(key) > 64 || keyLength > uint64(^uint32(0)) {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("%s - family key exceeds its validated bound: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
canonical = binary.BigEndian.AppendUint32(canonical, uint32(keyLength))
|
||||
canonical = append(canonical, key...)
|
||||
canonical = binary.BigEndian.AppendUint32(canonical, uint32(entry.Version))
|
||||
canonical = append(canonical, entry.ContentSHA256...)
|
||||
}
|
||||
return sha256.Sum256(canonical), nil
|
||||
}
|
||||
|
||||
func questionnaireTaskLanguageStrings(languages []domain.TaskLanguageCode) []string {
|
||||
values := make([]string, len(languages))
|
||||
for index, language := range languages {
|
||||
values[index] = string(language)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func questionnaireTaskLanguages(values []string) []domain.TaskLanguageCode {
|
||||
languages := make([]domain.TaskLanguageCode, len(values))
|
||||
for index, language := range values {
|
||||
languages[index] = domain.TaskLanguageCode(language)
|
||||
}
|
||||
return languages
|
||||
}
|
||||
|
||||
func questionnaireGradeRank(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 4
|
||||
}
|
||||
}
|
||||
|
||||
func questionnaireTaskLanguageRank(language domain.TaskLanguageCode) int {
|
||||
switch language {
|
||||
case domain.TaskLanguagePython:
|
||||
return 0
|
||||
case domain.TaskLanguageGo:
|
||||
return 1
|
||||
default:
|
||||
return 2
|
||||
}
|
||||
}
|
||||
|
||||
func mapAssessmentCatalogError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
switch {
|
||||
case pgError.Code == checkViolationCode && slices.Contains([]string{
|
||||
"assessment_category_catalog_bindings_specialization", "assessment_category_catalog_bindings_grade",
|
||||
"assessment_category_catalog_bindings_languages", "assessment_category_catalog_bindings_reviewer",
|
||||
"assessment_category_catalog_bindings_manifest_hash", "assessment_category_catalog_bindings_current_opening",
|
||||
"assessment_category_catalog_bindings_policy_current",
|
||||
"assessment_category_catalog_bindings_coverage",
|
||||
}, pgError.ConstraintName):
|
||||
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidAssessmentFamily)
|
||||
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
|
||||
"assessment_category_catalog_bindings_opening", "assessment_category_catalog_bindings_opening_fkey",
|
||||
}, pgError.ConstraintName):
|
||||
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCategoryNotOpen)
|
||||
case pgError.Code == integrityConstraintViolationCode && pgError.ConstraintName == "assessment_category_catalog_bindings_immutable":
|
||||
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCatalogBindingImmutable)
|
||||
default:
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"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.CandidateQuestionnaireRepository = candidateQuestionnaireRepository{}
|
||||
|
||||
func (unit *UnitOfWork) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
|
||||
return candidateQuestionnaireRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type candidateQuestionnaireRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
type storedQuestionnaireSpecialization struct {
|
||||
Ordinal int16 `json:"ordinal"`
|
||||
Specialization string `json:"specialization"`
|
||||
SelfAssessedGrade string `json:"self_assessed_grade"`
|
||||
TaskLanguages []string `json:"task_languages"`
|
||||
Stack []string `json:"stack"`
|
||||
CommercialMonths *int32 `json:"commercial_months"`
|
||||
AcademicMonths *int32 `json:"academic_months"`
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "candidateQuestionnaireRepository.Get"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
row, err := repository.queries.ReadCandidateQuestionnaire(ctx, pgUUID(userID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
questionnaire, err := domain.EmptyCandidateQuestionnaire(userID)
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - create empty questionnaire: %w", location, err)
|
||||
}
|
||||
return questionnaire, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - select questionnaire: %w", location, mapCandidateQuestionnaireError(err))
|
||||
}
|
||||
answers, err := decodeStoredQuestionnaireSpecializations(row.Specializations)
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore stored answers: %w", location, err)
|
||||
}
|
||||
stored := domain.StoredCandidateQuestionnaire{
|
||||
UserID: row.UserID.Bytes, Version: row.Version, Specializations: answers,
|
||||
WorkFormats: questionnaireWorkFormats(row.WorkFormats), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
||||
}
|
||||
questionnaire, err := domain.RestoreCandidateQuestionnaire(stored)
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore questionnaire: %w", location, err)
|
||||
}
|
||||
return questionnaire, nil
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) Save(
|
||||
ctx context.Context,
|
||||
expectedVersion int64,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "candidateQuestionnaireRepository.Save"
|
||||
if questionnaire.IsZero() || questionnaire.UserID() == uuid.Nil || questionnaire.Version() != expectedVersion ||
|
||||
expectedVersion < 0 || questionnaire.UpdatedAt().IsZero() {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - questionnaire or expected version is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
row, err := repository.advanceQuestionnaireVersion(ctx, expectedVersion, questionnaire)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return repository.readQuestionnaireWinner(ctx, questionnaire)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - advance version: %w", location, mapCandidateQuestionnaireError(err))
|
||||
}
|
||||
return repository.replaceQuestionnaireAnswers(ctx, questionnaire, row)
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) advanceQuestionnaireVersion(
|
||||
ctx context.Context,
|
||||
expectedVersion int64,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (sqlc.CandidateQuestionnaire, error) {
|
||||
workFormats := questionnaireWorkFormatStrings(questionnaire.WorkFormats())
|
||||
if expectedVersion == 0 {
|
||||
return repository.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
|
||||
UserID: pgUUID(questionnaire.UserID()), WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
|
||||
})
|
||||
}
|
||||
return repository.queries.AdvanceCandidateQuestionnaireVersion(ctx, sqlc.AdvanceCandidateQuestionnaireVersionParams{
|
||||
UserID: pgUUID(questionnaire.UserID()), ExpectedVersion: expectedVersion,
|
||||
WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
|
||||
})
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) readQuestionnaireWinner(
|
||||
ctx context.Context,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "candidateQuestionnaireRepository.readQuestionnaireWinner"
|
||||
winner, err := repository.Get(ctx, questionnaire.UserID())
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - read winner after compare-and-swap loss: %w", location, err)
|
||||
}
|
||||
if !winner.SameContent(questionnaire) {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - another questionnaire content won the version: %w", location, outbound.ErrCandidateQuestionnaireVersionConflict)
|
||||
}
|
||||
return winner, nil
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) replaceQuestionnaireAnswers(
|
||||
ctx context.Context,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
row sqlc.CandidateQuestionnaire,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "candidateQuestionnaireRepository.replaceQuestionnaireAnswers"
|
||||
if err := repository.queries.DeleteCandidateQuestionnaireSpecializations(ctx, pgUUID(questionnaire.UserID())); err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - delete old specialization answers: %w", location, mapCandidateQuestionnaireError(err))
|
||||
}
|
||||
answers := questionnaire.Specializations()
|
||||
for index, answer := range answers {
|
||||
ordinal, err := questionnaireSpecializationOrdinal(index)
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - encode answer order: %w", location, err)
|
||||
}
|
||||
commercialMonths, academicMonths := questionnaireExperienceMonths(answer.Experience)
|
||||
if err := repository.queries.InsertCandidateQuestionnaireSpecialization(ctx, sqlc.InsertCandidateQuestionnaireSpecializationParams{
|
||||
UserID: pgUUID(questionnaire.UserID()), Ordinal: ordinal,
|
||||
Specialization: string(answer.Specialization), SelfAssessedGrade: string(answer.SelfAssessedGrade),
|
||||
TaskLanguages: questionnaireTaskLanguageStrings(answer.TaskLanguages), Stack: slices.Clone(answer.Stack),
|
||||
CommercialMonths: commercialMonths, AcademicMonths: academicMonths,
|
||||
}); err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - insert specialization answer: %w", location, mapCandidateQuestionnaireError(err))
|
||||
}
|
||||
}
|
||||
stored := domain.StoredCandidateQuestionnaire{
|
||||
UserID: questionnaire.UserID(), Version: row.Version,
|
||||
Specializations: answers, WorkFormats: questionnaire.WorkFormats(),
|
||||
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
||||
}
|
||||
result, err := domain.RestoreCandidateQuestionnaire(stored)
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore saved questionnaire: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (repository candidateQuestionnaireRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
|
||||
const location = "candidateQuestionnaireRepository.AdvanceOnboarding"
|
||||
if userID == uuid.Nil || at.IsZero() {
|
||||
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
if err := repository.queries.AdvanceCandidateOnboardingAfterQuestionnaire(ctx, sqlc.AdvanceCandidateOnboardingAfterQuestionnaireParams{
|
||||
UserID: pgUUID(userID), At: pgTime(at),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - update onboarding: %w", location, mapCandidateQuestionnaireError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeStoredQuestionnaireSpecializations(encoded string) ([]domain.QuestionnaireSpecialization, error) {
|
||||
const location = "postgres.decodeStoredQuestionnaireSpecializations"
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var rows []storedQuestionnaireSpecialization
|
||||
if err := decoder.Decode(&rows); err != nil {
|
||||
return nil, fmt.Errorf("%s - stored answers have an unexpected shape: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return nil, fmt.Errorf("%s - stored answers have trailing data: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
answers := make([]domain.QuestionnaireSpecialization, 0, len(rows))
|
||||
for index, row := range rows {
|
||||
if int(row.Ordinal) != index || (row.CommercialMonths == nil) != (row.AcademicMonths == nil) {
|
||||
return nil, fmt.Errorf("%s - stored answer order or experience is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
answer := domain.QuestionnaireSpecialization{
|
||||
Specialization: domain.SpecializationCode(row.Specialization),
|
||||
SelfAssessedGrade: domain.GradeCode(row.SelfAssessedGrade),
|
||||
TaskLanguages: questionnaireTaskLanguages(row.TaskLanguages),
|
||||
Stack: slices.Clone(row.Stack),
|
||||
}
|
||||
if row.CommercialMonths != nil {
|
||||
answer.Experience = &domain.QuestionnaireExperience{
|
||||
CommercialMonths: *row.CommercialMonths,
|
||||
AcademicMonths: *row.AcademicMonths,
|
||||
}
|
||||
}
|
||||
answers = append(answers, answer)
|
||||
}
|
||||
return answers, nil
|
||||
}
|
||||
|
||||
func questionnaireExperienceMonths(experience *domain.QuestionnaireExperience) (pgtype.Int4, pgtype.Int4) {
|
||||
if experience == nil {
|
||||
return pgtype.Int4{}, pgtype.Int4{}
|
||||
}
|
||||
return pgtype.Int4{Int32: experience.CommercialMonths, Valid: true},
|
||||
pgtype.Int4{Int32: experience.AcademicMonths, Valid: true}
|
||||
}
|
||||
|
||||
func questionnaireSpecializationOrdinal(index int) (int16, error) {
|
||||
if index < 0 || index >= 2 {
|
||||
return 0, fmt.Errorf("postgres.questionnaireSpecializationOrdinal - order is outside the storage range: %w", domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
return int16(index), nil
|
||||
}
|
||||
|
||||
func questionnaireWorkFormats(values []string) []domain.QuestionnaireWorkFormat {
|
||||
formats := make([]domain.QuestionnaireWorkFormat, len(values))
|
||||
for index, value := range values {
|
||||
formats[index] = domain.QuestionnaireWorkFormat(value)
|
||||
}
|
||||
return formats
|
||||
}
|
||||
|
||||
func questionnaireWorkFormatStrings(values []domain.QuestionnaireWorkFormat) []string {
|
||||
formats := make([]string, len(values))
|
||||
for index, value := range values {
|
||||
formats[index] = string(value)
|
||||
}
|
||||
return formats
|
||||
}
|
||||
|
||||
func mapCandidateQuestionnaireError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
switch {
|
||||
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
|
||||
"candidate_questionnaires_user_fkey", "candidate_questionnaire_specializations_user_fkey",
|
||||
}, pgError.ConstraintName):
|
||||
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
|
||||
case pgError.Code == checkViolationCode && slices.Contains([]string{
|
||||
"candidate_questionnaires_version_positive", "candidate_questionnaires_work_formats", "candidate_questionnaires_times_ordered",
|
||||
"candidate_questionnaire_specializations_ordinal",
|
||||
"candidate_questionnaire_specializations_code", "candidate_questionnaire_specializations_grade",
|
||||
"candidate_questionnaire_specializations_languages", "candidate_questionnaire_specializations_stack",
|
||||
"candidate_questionnaire_specializations_experience",
|
||||
}, pgError.ConstraintName):
|
||||
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
|
||||
case pgError.Code == uniqueViolationCode && slices.Contains([]string{
|
||||
"candidate_questionnaires_pkey", "candidate_questionnaire_specializations_unique_code",
|
||||
}, pgError.ConstraintName):
|
||||
if pgError.ConstraintName == "candidate_questionnaire_specializations_unique_code" {
|
||||
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
return outbound.ErrCandidateQuestionnaireVersionConflict
|
||||
default:
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const companyQuotaViewCleanupBatchSize int32 = 100
|
||||
|
||||
func (unit *UnitOfWork) CompanyQuotas() outbound.CompanyQuotaRepository {
|
||||
return companyQuotaRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type companyQuotaRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.CompanyQuotaRepository = companyQuotaRepository{}
|
||||
|
||||
func (repository companyQuotaRepository) ReserveInvitation(
|
||||
ctx context.Context,
|
||||
quota domain.CompanyQuota,
|
||||
invitationID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "companyQuotaRepository.ReserveInvitation"
|
||||
if err := validateCompanyQuota(location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if invitationID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
organizationID := pgUUID(quota.OrganizationID())
|
||||
invitation, err := repository.queries.FindCompanyInvitationQuotaUsage(ctx, sqlc.FindCompanyInvitationQuotaUsageParams{
|
||||
OrganizationID: organizationID,
|
||||
InvitationID: pgUUID(invitationID),
|
||||
})
|
||||
if err == nil {
|
||||
if !invitation.Valid || invitation.Bytes != invitationID {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - existing invitation usage did not match its key", location)
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
|
||||
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
|
||||
OrganizationID: organizationID,
|
||||
WindowStart: pgTime(quota.InvitationWindowStart()),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
|
||||
}
|
||||
if usage.UsageCount >= quota.InvitationLimit() {
|
||||
earliest, err := quotaWindowEarliest(usage.EarliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.InvitationWindow()).UTC()}, nil
|
||||
}
|
||||
if err := repository.queries.InsertCompanyInvitationQuotaUsage(ctx, companyInvitationUsageParams(quota, invitationID)); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - insert invitation usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) ReserveCardView(
|
||||
ctx context.Context,
|
||||
quota domain.CompanyQuota,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "companyQuotaRepository.ReserveCardView"
|
||||
if err := validateCompanyQuota(location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if candidateID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
organizationID := quota.OrganizationID()
|
||||
decision, handled, err := repository.reserveExistingCardView(ctx, location, quota, organizationID, candidateID)
|
||||
if err != nil || handled {
|
||||
return decision, err
|
||||
}
|
||||
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) reserveExistingCardView(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
organizationID uuid.UUID,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, bool, error) {
|
||||
existing, findErr := repository.queries.FindCompanyCardViewQuotaUsage(ctx, sqlc.FindCompanyCardViewQuotaUsageParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
CandidateID: pgUUID(candidateID),
|
||||
})
|
||||
if errors.Is(findErr, pgx.ErrNoRows) {
|
||||
return outbound.CompanyQuotaDecision{}, false, nil
|
||||
}
|
||||
if findErr != nil {
|
||||
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - read card-view usage: %w", location, mapOrganizationError(findErr))
|
||||
}
|
||||
if !existing.Valid {
|
||||
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - existing card-view timestamp is invalid", location)
|
||||
}
|
||||
if !existing.Time.After(quota.CardViewWindowStart()) {
|
||||
return outbound.CompanyQuotaDecision{}, false, nil
|
||||
}
|
||||
decision, err := repository.refreshActiveCardView(ctx, location, quota, organizationID, candidateID)
|
||||
return decision, true, err
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) refreshActiveCardView(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
organizationID uuid.UUID,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
updated, err := repository.queries.RefreshCompanyCardViewQuotaUsage(ctx, sqlc.RefreshCompanyCardViewQuotaUsageParams{
|
||||
LastSeenAt: pgTime(quota.At()),
|
||||
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
|
||||
VerificationLevel: string(quota.VerificationLevel()),
|
||||
VerificationBasis: string(quota.VerificationBasis()),
|
||||
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
|
||||
QuotaTier: string(quota.Tier()),
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
CandidateID: pgUUID(candidateID),
|
||||
WindowStart: pgTime(quota.CardViewWindowStart()),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - refresh card-view usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if updated != 1 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - active card-view usage changed while organization was locked", location)
|
||||
}
|
||||
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) reserveNewCardView(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
candidateID uuid.UUID,
|
||||
organizationID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
WindowStart: pgTime(quota.CardViewWindowStart()),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
|
||||
}
|
||||
if usage.UsageCount >= quota.CardViewLimit() {
|
||||
earliest, err := quotaWindowEarliest(usage.EarliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.CardViewWindow()).UTC()}, nil
|
||||
}
|
||||
if err := repository.queries.SaveCompanyCardViewQuotaUsage(ctx, companyCardViewUsageParams(quota, candidateID)); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - save card-view usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
) error {
|
||||
organizationID := pgUUID(quota.OrganizationID())
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() ||
|
||||
!organization.VerificationChangedAt.Valid ||
|
||||
organization.VerificationLevel != string(quota.VerificationLevel()) ||
|
||||
organization.VerificationBasis != string(quota.VerificationBasis()) ||
|
||||
!organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) {
|
||||
return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
|
||||
policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
|
||||
PolicyKey: string(domain.ProductPolicyKey),
|
||||
At: pgTime(quota.At()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - no effective product policy remains: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - recheck effective product policy: %w", location, mapPolicyError(err))
|
||||
}
|
||||
if !policy.ID.Valid || policy.ID.Bytes != quota.PolicyVersionID().UUID() || policy.PolicyKey != string(domain.ProductPolicyKey) {
|
||||
return fmt.Errorf("%s - effective product policy changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) cleanupExpiredCardViews(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
) error {
|
||||
_, err := repository.queries.DeleteExpiredCompanyCardViewQuotaUsage(ctx, sqlc.DeleteExpiredCompanyCardViewQuotaUsageParams{
|
||||
OrganizationID: pgUUID(quota.OrganizationID()),
|
||||
WindowStart: pgTime(quota.CardViewWindowStart()),
|
||||
RowLimit: companyQuotaViewCleanupBatchSize,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - clean expired card-view usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCompanyQuota(location string, quota domain.CompanyQuota) error {
|
||||
if quota.IsZero() || quota.OrganizationID() == uuid.Nil || quota.PolicyVersionID().UUID() == uuid.Nil ||
|
||||
quota.At().IsZero() || quota.At().Unix() < 0 ||
|
||||
quota.InvitationWindow() <= 0 || quota.InvitationLimit() <= 0 ||
|
||||
quota.CardViewWindow() <= 0 || quota.CardViewLimit() <= 0 ||
|
||||
quota.InvitationWindowStart().IsZero() || quota.CardViewWindowStart().IsZero() {
|
||||
return fmt.Errorf("%s - quota snapshot was not built from an active policy and stored organization: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func quotaWindowEarliest(value interface{}) (time.Time, error) {
|
||||
switch timestamp := value.(type) {
|
||||
case time.Time:
|
||||
if timestamp.IsZero() {
|
||||
return time.Time{}, errors.New("window timestamp is zero")
|
||||
}
|
||||
return timestamp.UTC(), nil
|
||||
case *time.Time:
|
||||
if timestamp == nil || timestamp.IsZero() {
|
||||
return time.Time{}, errors.New("window timestamp is missing")
|
||||
}
|
||||
return timestamp.UTC(), nil
|
||||
default:
|
||||
return time.Time{}, errors.New("window timestamp has an unexpected database value")
|
||||
}
|
||||
}
|
||||
|
||||
func companyInvitationUsageParams(quota domain.CompanyQuota, invitationID uuid.UUID) sqlc.InsertCompanyInvitationQuotaUsageParams {
|
||||
return sqlc.InsertCompanyInvitationQuotaUsageParams{
|
||||
OrganizationID: pgUUID(quota.OrganizationID()),
|
||||
InvitationID: pgUUID(invitationID),
|
||||
ReservedAt: pgTime(quota.At()),
|
||||
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
|
||||
VerificationLevel: string(quota.VerificationLevel()),
|
||||
VerificationBasis: string(quota.VerificationBasis()),
|
||||
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
|
||||
QuotaTier: string(quota.Tier()),
|
||||
}
|
||||
}
|
||||
|
||||
func companyCardViewUsageParams(quota domain.CompanyQuota, candidateID uuid.UUID) sqlc.SaveCompanyCardViewQuotaUsageParams {
|
||||
return sqlc.SaveCompanyCardViewQuotaUsageParams{
|
||||
OrganizationID: pgUUID(quota.OrganizationID()),
|
||||
CandidateID: pgUUID(candidateID),
|
||||
LastSeenAt: pgTime(quota.At()),
|
||||
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
|
||||
VerificationLevel: string(quota.VerificationLevel()),
|
||||
VerificationBasis: string(quota.VerificationBasis()),
|
||||
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
|
||||
QuotaTier: string(quota.Tier()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: company_quota.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(last_seen_at) AS earliest_at
|
||||
FROM company_card_view_quota_usage
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND last_seen_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyCardViewQuotaWindowParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyCardViewQuotaWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaWindow, arg.OrganizationID, arg.WindowStart)
|
||||
var i CountCompanyCardViewQuotaWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(reserved_at) AS earliest_at
|
||||
FROM company_invitation_quota_usage
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND reserved_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyInvitationQuotaWindowParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyInvitationQuotaWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
func (q *Queries) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaWindow, arg.OrganizationID, arg.WindowStart)
|
||||
var i CountCompanyInvitationQuotaWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteExpiredCompanyCardViewQuotaUsage = `-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows
|
||||
WITH expired AS (
|
||||
SELECT quota_usage.organization_id, quota_usage.candidate_id
|
||||
FROM company_card_view_quota_usage AS quota_usage
|
||||
WHERE
|
||||
quota_usage.organization_id = $1
|
||||
AND quota_usage.last_seen_at <= $2
|
||||
ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id
|
||||
LIMIT $3::integer
|
||||
)
|
||||
DELETE FROM company_card_view_quota_usage AS usage
|
||||
USING expired
|
||||
WHERE
|
||||
usage.organization_id = expired.organization_id
|
||||
AND usage.candidate_id = expired.candidate_id
|
||||
`
|
||||
|
||||
type DeleteExpiredCompanyCardViewQuotaUsageParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteExpiredCompanyCardViewQuotaUsage, arg.OrganizationID, arg.WindowStart, arg.RowLimit)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const findCompanyCardViewQuotaUsage = `-- name: FindCompanyCardViewQuotaUsage :one
|
||||
SELECT last_seen_at
|
||||
FROM company_card_view_quota_usage
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND candidate_id = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type FindCompanyCardViewQuotaUsageParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error) {
|
||||
row := q.db.QueryRow(ctx, findCompanyCardViewQuotaUsage, arg.OrganizationID, arg.CandidateID)
|
||||
var last_seen_at pgtype.Timestamptz
|
||||
err := row.Scan(&last_seen_at)
|
||||
return last_seen_at, err
|
||||
}
|
||||
|
||||
const findCompanyInvitationQuotaUsage = `-- name: FindCompanyInvitationQuotaUsage :one
|
||||
SELECT invitation_id
|
||||
FROM company_invitation_quota_usage
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND invitation_id = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type FindCompanyInvitationQuotaUsageParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, findCompanyInvitationQuotaUsage, arg.OrganizationID, arg.InvitationID)
|
||||
var invitation_id pgtype.UUID
|
||||
err := row.Scan(&invitation_id)
|
||||
return invitation_id, err
|
||||
}
|
||||
|
||||
const insertCompanyInvitationQuotaUsage = `-- name: InsertCompanyInvitationQuotaUsage :exec
|
||||
INSERT INTO company_invitation_quota_usage (
|
||||
organization_id,
|
||||
invitation_id,
|
||||
reserved_at,
|
||||
policy_version_id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
quota_tier
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
`
|
||||
|
||||
type InsertCompanyInvitationQuotaUsageParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
ReservedAt pgtype.Timestamptz
|
||||
PolicyVersionID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
QuotaTier string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error {
|
||||
_, err := q.db.Exec(ctx, insertCompanyInvitationQuotaUsage,
|
||||
arg.OrganizationID,
|
||||
arg.InvitationID,
|
||||
arg.ReservedAt,
|
||||
arg.PolicyVersionID,
|
||||
arg.VerificationLevel,
|
||||
arg.VerificationBasis,
|
||||
arg.VerificationChangedAt,
|
||||
arg.QuotaTier,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
|
||||
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at
|
||||
FROM organizations
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockCompanyQuotaOrganizationRow struct {
|
||||
ID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID)
|
||||
var i LockCompanyQuotaOrganizationRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.VerificationLevel,
|
||||
&i.VerificationBasis,
|
||||
&i.VerificationChangedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
|
||||
UPDATE company_card_view_quota_usage
|
||||
SET
|
||||
last_seen_at = greatest(last_seen_at, $1),
|
||||
policy_version_id = $2,
|
||||
verification_level = $3,
|
||||
verification_basis = $4,
|
||||
verification_changed_at = $5,
|
||||
quota_tier = $6
|
||||
WHERE
|
||||
organization_id = $7
|
||||
AND candidate_id = $8
|
||||
AND last_seen_at > $9
|
||||
`
|
||||
|
||||
type RefreshCompanyCardViewQuotaUsageParams struct {
|
||||
LastSeenAt pgtype.Timestamptz
|
||||
PolicyVersionID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
QuotaTier string
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, refreshCompanyCardViewQuotaUsage,
|
||||
arg.LastSeenAt,
|
||||
arg.PolicyVersionID,
|
||||
arg.VerificationLevel,
|
||||
arg.VerificationBasis,
|
||||
arg.VerificationChangedAt,
|
||||
arg.QuotaTier,
|
||||
arg.OrganizationID,
|
||||
arg.CandidateID,
|
||||
arg.WindowStart,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const saveCompanyCardViewQuotaUsage = `-- name: SaveCompanyCardViewQuotaUsage :exec
|
||||
INSERT INTO company_card_view_quota_usage (
|
||||
organization_id,
|
||||
candidate_id,
|
||||
last_seen_at,
|
||||
policy_version_id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
quota_tier
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (organization_id, candidate_id)
|
||||
DO UPDATE SET
|
||||
last_seen_at = greatest(
|
||||
company_card_view_quota_usage.last_seen_at,
|
||||
EXCLUDED.last_seen_at
|
||||
),
|
||||
policy_version_id = EXCLUDED.policy_version_id,
|
||||
verification_level = EXCLUDED.verification_level,
|
||||
verification_basis = EXCLUDED.verification_basis,
|
||||
verification_changed_at = EXCLUDED.verification_changed_at,
|
||||
quota_tier = EXCLUDED.quota_tier
|
||||
`
|
||||
|
||||
type SaveCompanyCardViewQuotaUsageParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
LastSeenAt pgtype.Timestamptz
|
||||
PolicyVersionID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
QuotaTier string
|
||||
}
|
||||
|
||||
func (q *Queries) SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error {
|
||||
_, err := q.db.Exec(ctx, saveCompanyCardViewQuotaUsage,
|
||||
arg.OrganizationID,
|
||||
arg.CandidateID,
|
||||
arg.LastSeenAt,
|
||||
arg.PolicyVersionID,
|
||||
arg.VerificationLevel,
|
||||
arg.VerificationBasis,
|
||||
arg.VerificationChangedAt,
|
||||
arg.QuotaTier,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -16,6 +16,16 @@ type AccountDeletionRequest struct {
|
||||
CompletedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentCategoryCatalogBinding struct {
|
||||
OpeningID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
TaskLanguages []string
|
||||
PublishedManifestSha256 []byte
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentCategoryOpening struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
@@ -124,6 +134,25 @@ type CandidatePublication struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateQuestionnaire struct {
|
||||
UserID pgtype.UUID
|
||||
Version int64
|
||||
WorkFormats []string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateQuestionnaireSpecialization struct {
|
||||
UserID pgtype.UUID
|
||||
Ordinal int16
|
||||
Specialization string
|
||||
SelfAssessedGrade string
|
||||
TaskLanguages []string
|
||||
Stack []string
|
||||
CommercialMonths pgtype.Int4
|
||||
AcademicMonths pgtype.Int4
|
||||
}
|
||||
|
||||
type CandidateSearchStatus struct {
|
||||
UserID pgtype.UUID
|
||||
Status string
|
||||
@@ -135,6 +164,28 @@ type CandidateSearchStatus struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CompanyCardViewQuotaUsage struct {
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
LastSeenAt pgtype.Timestamptz
|
||||
PolicyVersionID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
QuotaTier string
|
||||
}
|
||||
|
||||
type CompanyInvitationQuotaUsage struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
ReservedAt pgtype.Timestamptz
|
||||
PolicyVersionID pgtype.UUID
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
QuotaTier string
|
||||
}
|
||||
|
||||
type ConsentRecord struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
|
||||
@@ -17,6 +17,8 @@ type Querier interface {
|
||||
// Saving a profile advances onboarding only from that exact step. A retry or
|
||||
// a save after a later step is already stored never regresses onboarding.
|
||||
AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error
|
||||
// A questionnaire save advances onboarding only from its own step.
|
||||
AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error
|
||||
// Advances the version over the one the caller read, in the same statement.
|
||||
// The row lock it takes serializes concurrent saves of one profile. The update
|
||||
// time never moves back: an application clock behind the stored time (clock
|
||||
@@ -25,6 +27,9 @@ type Querier interface {
|
||||
// returns for a stale version or for an account without a profile, which the
|
||||
// caller answers as a version conflict.
|
||||
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
|
||||
// Advances an existing questionnaire only at the version read by the caller.
|
||||
// The row lock serializes saves for one user; a stale writer returns no row.
|
||||
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
|
||||
// Starts a new registration of an unverified account without touching its
|
||||
// credentials, scenario, or onboarding step: the new registration carries
|
||||
// them on its verification token. Advances the registration version, which
|
||||
@@ -110,6 +115,8 @@ type Querier interface {
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, 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)
|
||||
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
|
||||
// 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)
|
||||
@@ -127,6 +134,10 @@ type Querier interface {
|
||||
// Replaces the current explicit decisions with those in the new profile.
|
||||
// The versioned profile row is advanced first in this same transaction.
|
||||
DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error
|
||||
// Replaces all specialization answers after the version row advanced in the
|
||||
// same transaction.
|
||||
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) 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
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
@@ -165,6 +176,8 @@ type Querier interface {
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
// completion applies.
|
||||
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
|
||||
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
|
||||
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
|
||||
// Returns the newest open reservation of a delivery under a provider account
|
||||
// made at or after reserved_since. A retry of the delivery inside the
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
@@ -260,6 +273,10 @@ 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)
|
||||
// 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.
|
||||
InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error
|
||||
// Stores an opening. The insert trigger derives required_families from the
|
||||
// policy document and counts the published families, and the coverage CHECK
|
||||
// refuses the row when they are fewer; both numbers from the caller are
|
||||
@@ -301,8 +318,13 @@ type Querier interface {
|
||||
// one is answered as a version conflict. The foreign key refuses a record
|
||||
// that is not a C2 record of this account.
|
||||
InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error)
|
||||
// Creates the first saved questionnaire. A missing row is version zero;
|
||||
// concurrent first saves race on the primary key and exactly one returns a row.
|
||||
InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error)
|
||||
InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error
|
||||
// Stores the first status at version 1; no row returns when one exists.
|
||||
InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error)
|
||||
InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error
|
||||
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
|
||||
// subject, purpose, and text version already exists when no row returns;
|
||||
// the insert then changes nothing and does not abort the transaction.
|
||||
@@ -384,6 +406,10 @@ type Querier interface {
|
||||
// the last record of the previous page.
|
||||
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, 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)
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
@@ -413,6 +439,10 @@ type Querier interface {
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
// other workers skip the row, so the handler never runs twice at once.
|
||||
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// 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)
|
||||
// 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
|
||||
@@ -496,6 +526,9 @@ type Querier interface {
|
||||
// snapshot. The effective state is computed from them: published only while
|
||||
// consent_revoked_at is NULL. No row means the candidate never published.
|
||||
ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error)
|
||||
// Reads the aggregate and its ordered specializations in one statement so a
|
||||
// response never pairs a version with another version's answers.
|
||||
ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error)
|
||||
// No row means the status was never set, which reads as not looking. The
|
||||
// lapse is computed by the caller from lapses_at and its clock and is never
|
||||
// written.
|
||||
@@ -507,6 +540,10 @@ type Querier interface {
|
||||
// unpublished one. Every organization-facing read of a publication starts
|
||||
// from this shape.
|
||||
ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error)
|
||||
// Lists the exact published bank manifest while the category advisory lock is
|
||||
// held by OpenCategory. Published families have passed the independent-review
|
||||
// constraint before this read.
|
||||
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, 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
|
||||
@@ -534,6 +571,7 @@ type Querier interface {
|
||||
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
|
||||
// Records the latest settled outcome of a send under the reservation.
|
||||
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
|
||||
RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error)
|
||||
// Gives a claimed delivery back without changing it, so the next pass may
|
||||
// claim it. It matches only the lease of lease_owner: a delivery that another
|
||||
// worker took over after the lease expired is left alone.
|
||||
@@ -568,6 +606,7 @@ type Querier interface {
|
||||
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
|
||||
// Stores the immutable domain snapshot of a successful create command. The
|
||||
// generic idempotency row and this result are committed with the organization
|
||||
// and owner membership. A reused expired scope replaces the snapshot in the
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: questionnaire.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const advanceCandidateOnboardingAfterQuestionnaire = `-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec
|
||||
UPDATE users
|
||||
SET
|
||||
onboarding_step = 'candidate_assessment',
|
||||
version = users.version + 1,
|
||||
updated_at = GREATEST(users.updated_at, $1::timestamptz)
|
||||
WHERE
|
||||
users.id = $2
|
||||
AND users.scenario = 'candidate'
|
||||
AND users.email_verified_at IS NOT NULL
|
||||
AND users.onboarding_step = 'candidate_questionnaire'
|
||||
`
|
||||
|
||||
type AdvanceCandidateOnboardingAfterQuestionnaireParams struct {
|
||||
At pgtype.Timestamptz
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
// A questionnaire save advances onboarding only from its own step.
|
||||
func (q *Queries) AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error {
|
||||
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterQuestionnaire, arg.At, arg.UserID)
|
||||
return err
|
||||
}
|
||||
|
||||
const advanceCandidateQuestionnaireVersion = `-- name: AdvanceCandidateQuestionnaireVersion :one
|
||||
UPDATE candidate_questionnaires
|
||||
SET
|
||||
version = candidate_questionnaires.version + 1,
|
||||
work_formats = $1,
|
||||
updated_at = GREATEST(candidate_questionnaires.updated_at, $2::timestamptz)
|
||||
WHERE
|
||||
candidate_questionnaires.user_id = $3
|
||||
AND candidate_questionnaires.version = $4
|
||||
RETURNING user_id, version, work_formats, created_at, updated_at
|
||||
`
|
||||
|
||||
type AdvanceCandidateQuestionnaireVersionParams struct {
|
||||
WorkFormats []string
|
||||
At pgtype.Timestamptz
|
||||
UserID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
}
|
||||
|
||||
// Advances an existing questionnaire only at the version read by the caller.
|
||||
// The row lock serializes saves for one user; a stale writer returns no row.
|
||||
func (q *Queries) AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error) {
|
||||
row := q.db.QueryRow(ctx, advanceCandidateQuestionnaireVersion,
|
||||
arg.WorkFormats,
|
||||
arg.At,
|
||||
arg.UserID,
|
||||
arg.ExpectedVersion,
|
||||
)
|
||||
var i CandidateQuestionnaire
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.Version,
|
||||
&i.WorkFormats,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteCandidateQuestionnaireSpecializations = `-- name: DeleteCandidateQuestionnaireSpecializations :exec
|
||||
DELETE FROM candidate_questionnaire_specializations
|
||||
WHERE user_id = $1
|
||||
`
|
||||
|
||||
// Replaces all specialization answers after the version row advanced in the
|
||||
// same transaction.
|
||||
func (q *Queries) DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deleteCandidateQuestionnaireSpecializations, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertAssessmentCategoryCatalogBinding = `-- name: InsertAssessmentCategoryCatalogBinding :exec
|
||||
INSERT INTO assessment_category_catalog_bindings (
|
||||
opening_id,
|
||||
specialization,
|
||||
grade,
|
||||
task_languages,
|
||||
published_manifest_sha256,
|
||||
reviewed_by,
|
||||
reviewed_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
clock_timestamp()
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentCategoryCatalogBindingParams struct {
|
||||
OpeningID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
TaskLanguages []string
|
||||
PublishedManifestSha256 []byte
|
||||
ReviewedBy string
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (q *Queries) InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentCategoryCatalogBinding,
|
||||
arg.OpeningID,
|
||||
arg.Specialization,
|
||||
arg.Grade,
|
||||
arg.TaskLanguages,
|
||||
arg.PublishedManifestSha256,
|
||||
arg.ReviewedBy,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertCandidateQuestionnaire = `-- name: InsertCandidateQuestionnaire :one
|
||||
INSERT INTO candidate_questionnaires (
|
||||
user_id,
|
||||
version,
|
||||
work_formats,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
$1,
|
||||
1,
|
||||
$2,
|
||||
$3::timestamptz,
|
||||
$3::timestamptz
|
||||
)
|
||||
ON CONFLICT (user_id) DO NOTHING
|
||||
RETURNING user_id, version, work_formats, created_at, updated_at
|
||||
`
|
||||
|
||||
type InsertCandidateQuestionnaireParams struct {
|
||||
UserID pgtype.UUID
|
||||
WorkFormats []string
|
||||
At pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Creates the first saved questionnaire. A missing row is version zero;
|
||||
// concurrent first saves race on the primary key and exactly one returns a row.
|
||||
func (q *Queries) InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error) {
|
||||
row := q.db.QueryRow(ctx, insertCandidateQuestionnaire, arg.UserID, arg.WorkFormats, arg.At)
|
||||
var i CandidateQuestionnaire
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.Version,
|
||||
&i.WorkFormats,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertCandidateQuestionnaireSpecialization = `-- name: InsertCandidateQuestionnaireSpecialization :exec
|
||||
INSERT INTO candidate_questionnaire_specializations (
|
||||
user_id,
|
||||
ordinal,
|
||||
specialization,
|
||||
self_assessed_grade,
|
||||
task_languages,
|
||||
stack,
|
||||
commercial_months,
|
||||
academic_months
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
`
|
||||
|
||||
type InsertCandidateQuestionnaireSpecializationParams struct {
|
||||
UserID pgtype.UUID
|
||||
Ordinal int16
|
||||
Specialization string
|
||||
SelfAssessedGrade string
|
||||
TaskLanguages []string
|
||||
Stack []string
|
||||
CommercialMonths pgtype.Int4
|
||||
AcademicMonths pgtype.Int4
|
||||
}
|
||||
|
||||
func (q *Queries) InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error {
|
||||
_, err := q.db.Exec(ctx, insertCandidateQuestionnaireSpecialization,
|
||||
arg.UserID,
|
||||
arg.Ordinal,
|
||||
arg.Specialization,
|
||||
arg.SelfAssessedGrade,
|
||||
arg.TaskLanguages,
|
||||
arg.Stack,
|
||||
arg.CommercialMonths,
|
||||
arg.AcademicMonths,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listCurrentSpecializationAvailability = `-- name: ListCurrentSpecializationAvailability :many
|
||||
WITH current_policy AS (
|
||||
SELECT id
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
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,
|
||||
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 opening.category
|
||||
`
|
||||
|
||||
type ListCurrentSpecializationAvailabilityRow struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
PolicyVersionID pgtype.UUID
|
||||
RequiredFamilies int32
|
||||
PublishedCount int32
|
||||
EffectivePolicyID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
TaskLanguages []string
|
||||
PublishedManifestSha256 []byte
|
||||
PublishedManifest string
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (q *Queries) ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCurrentSpecializationAvailability)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCurrentSpecializationAvailabilityRow
|
||||
for rows.Next() {
|
||||
var i ListCurrentSpecializationAvailabilityRow
|
||||
if err := rows.Scan(
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.PolicyVersionID,
|
||||
&i.RequiredFamilies,
|
||||
&i.PublishedCount,
|
||||
&i.EffectivePolicyID,
|
||||
&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 readCandidateQuestionnaire = `-- name: ReadCandidateQuestionnaire :one
|
||||
SELECT
|
||||
questionnaire.user_id,
|
||||
questionnaire.version,
|
||||
questionnaire.work_formats,
|
||||
questionnaire.created_at,
|
||||
questionnaire.updated_at,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'ordinal', specialization.ordinal,
|
||||
'specialization', specialization.specialization,
|
||||
'self_assessed_grade', specialization.self_assessed_grade,
|
||||
'task_languages', specialization.task_languages,
|
||||
'stack', specialization.stack,
|
||||
'commercial_months', specialization.commercial_months,
|
||||
'academic_months', specialization.academic_months
|
||||
) ORDER BY specialization.ordinal
|
||||
)
|
||||
FROM candidate_questionnaire_specializations AS specialization
|
||||
WHERE specialization.user_id = questionnaire.user_id
|
||||
), '[]'::jsonb)::text AS specializations
|
||||
FROM candidate_questionnaires AS questionnaire
|
||||
WHERE questionnaire.user_id = $1
|
||||
`
|
||||
|
||||
type ReadCandidateQuestionnaireRow struct {
|
||||
UserID pgtype.UUID
|
||||
Version int64
|
||||
WorkFormats []string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
Specializations string
|
||||
}
|
||||
|
||||
// Reads the aggregate and its ordered specializations in one statement so a
|
||||
// response never pairs a version with another version's answers.
|
||||
func (q *Queries) ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error) {
|
||||
row := q.db.QueryRow(ctx, readCandidateQuestionnaire, userID)
|
||||
var i ReadCandidateQuestionnaireRow
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.Version,
|
||||
&i.WorkFormats,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Specializations,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const readPublishedAssessmentCategoryManifest = `-- name: ReadPublishedAssessmentCategoryManifest :many
|
||||
SELECT family_key, version, content_sha256
|
||||
FROM assessment_families
|
||||
WHERE category = $1 AND lifecycle = 'published'
|
||||
ORDER BY family_key, version
|
||||
`
|
||||
|
||||
type ReadPublishedAssessmentCategoryManifestRow struct {
|
||||
FamilyKey string
|
||||
Version int32
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
// Lists the exact published bank manifest while the category advisory lock is
|
||||
// held by OpenCategory. Published families have passed the independent-review
|
||||
// constraint before this read.
|
||||
func (q *Queries) ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error) {
|
||||
rows, err := q.db.Query(ctx, readPublishedAssessmentCategoryManifest, category)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ReadPublishedAssessmentCategoryManifestRow
|
||||
for rows.Next() {
|
||||
var i ReadPublishedAssessmentCategoryManifestRow
|
||||
if err := rows.Scan(&i.FamilyKey, &i.Version, &i.ContentSha256); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
const catalogPoolMaxConns = 4
|
||||
|
||||
func newCatalogHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.CatalogHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("specialization catalog is not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, catalogPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
bank := assessment.NewBank(postgres.NewTransactor(pool))
|
||||
return v1.NewCatalogHandler(bank), pool.Close, nil
|
||||
}
|
||||
@@ -37,12 +37,16 @@ func newAPIHandler(
|
||||
identityHandler *v1.IdentityHandler,
|
||||
consentHandler *v1.ConsentHandler,
|
||||
profileHandler *v1.ProfileHandler,
|
||||
questionnaireHandler *v1.QuestionnaireHandler,
|
||||
catalogHandler *v1.CatalogHandler,
|
||||
organizationHandler *v1.OrganizationHandler,
|
||||
) *v1.Handler {
|
||||
return v1.NewHandler(health, problems,
|
||||
v1.WithIdentity(identityHandler),
|
||||
v1.WithConsent(consentHandler),
|
||||
v1.WithProfile(profileHandler),
|
||||
v1.WithQuestionnaire(questionnaireHandler),
|
||||
v1.WithCatalog(catalogHandler),
|
||||
v1.WithOrganization(organizationHandler),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/questionnaire"
|
||||
)
|
||||
|
||||
const questionnairePoolMaxConns = 8
|
||||
|
||||
func newQuestionnaireHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.QuestionnaireHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("candidate questionnaire operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, questionnairePoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
service := questionnaire.NewService(postgres.NewTransactor(pool), time.Now)
|
||||
return v1.NewQuestionnaireHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -49,6 +49,8 @@ func initialize(
|
||||
newIdentityKeyring,
|
||||
newConsentHandler,
|
||||
newProfileHandler,
|
||||
newQuestionnaireHandler,
|
||||
newCatalogHandler,
|
||||
newOrganizationHandler,
|
||||
newSessionSecurity,
|
||||
newRouter,
|
||||
|
||||
@@ -76,7 +76,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
organizationHandler, cleanup7, err := newOrganizationHandler(ctx, config2, logger, keyring)
|
||||
questionnaireHandler, cleanup7, err := newQuestionnaireHandler(ctx, config2, logger)
|
||||
if err != nil {
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
@@ -86,10 +86,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, organizationHandler)
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
|
||||
catalogHandler, cleanup8, err := newCatalogHandler(ctx, config2, logger)
|
||||
if err != nil {
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
@@ -100,18 +97,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
relay, cleanup8, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup9, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
organizationHandler, cleanup9, err := newOrganizationHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
@@ -123,7 +109,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
worker, cleanup10, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
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)
|
||||
if err != nil {
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
@@ -136,7 +125,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
mailsenderWorker, cleanup11, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
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)
|
||||
if err != nil {
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
@@ -150,7 +152,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup12, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
worker, cleanup12, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
@@ -165,8 +167,43 @@ 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)
|
||||
if err != nil {
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup14, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
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() {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// AssessmentCategoryCatalogMetadata is the explicit public-catalog mapping
|
||||
// reviewed for a published bank category before it is opened. It does not
|
||||
// derive public specialization from an assessment family's internal topic.
|
||||
type AssessmentCategoryCatalogMetadata struct {
|
||||
specialization SpecializationCode
|
||||
grade GradeCode
|
||||
taskLanguages []TaskLanguageCode
|
||||
}
|
||||
|
||||
// NewAssessmentCategoryCatalogMetadata validates the mapping attached to a
|
||||
// reviewed category opening.
|
||||
func NewAssessmentCategoryCatalogMetadata(
|
||||
specialization SpecializationCode,
|
||||
grade GradeCode,
|
||||
taskLanguages []TaskLanguageCode,
|
||||
) (AssessmentCategoryCatalogMetadata, error) {
|
||||
const location = "domain.NewAssessmentCategoryCatalogMetadata"
|
||||
if !specialization.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - specialization is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if !grade.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - grade is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if len(taskLanguages) > maxQuestionnaireTaskLanguages {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - at most two task languages are allowed: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
seen := make(map[TaskLanguageCode]struct{}, len(taskLanguages))
|
||||
for _, language := range taskLanguages {
|
||||
if !language.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task language is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if _, exists := seen[language]; exists {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task languages must be unique: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
seen[language] = struct{}{}
|
||||
}
|
||||
return AssessmentCategoryCatalogMetadata{
|
||||
specialization: specialization,
|
||||
grade: grade,
|
||||
taskLanguages: slices.Clone(taskLanguages),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) Specialization() SpecializationCode {
|
||||
return metadata.specialization
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) Grade() GradeCode { return metadata.grade }
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) TaskLanguages() []TaskLanguageCode {
|
||||
return slices.Clone(metadata.taskLanguages)
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) IsZero() bool {
|
||||
return metadata.specialization == "" || metadata.grade == ""
|
||||
}
|
||||
|
||||
// AssessmentCategoryManifestEntry is an immutable published family identity
|
||||
// used to pin public catalog metadata to one reviewed bank composition.
|
||||
type AssessmentCategoryManifestEntry struct {
|
||||
FamilyKey AssessmentFamilyKey
|
||||
Version int32
|
||||
ContentSHA256 []byte
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidCompanyQuota reports a quota request that has incomplete or
|
||||
// inconsistent trusted inputs.
|
||||
ErrInvalidCompanyQuota = errors.New("invalid company quota")
|
||||
|
||||
// ErrCompanyQuotaDenied reports an organization level that has no active
|
||||
// quota tier. Callers must refuse the action instead of falling back.
|
||||
ErrCompanyQuotaDenied = errors.New("company quota denied")
|
||||
)
|
||||
|
||||
// CompanyQuota is an immutable snapshot of the limits that apply to one
|
||||
// organization at one instant. It carries the stored verification and
|
||||
// effective policy identities so the transactional repository can verify
|
||||
// that neither changed before it reserves usage.
|
||||
type CompanyQuota struct {
|
||||
organizationID uuid.UUID
|
||||
policyVersionID PolicyVersionID
|
||||
verificationLevel OrganizationVerificationLevel
|
||||
verificationBasis OrganizationVerificationBasis
|
||||
verificationChanged time.Time
|
||||
tier OrganizationTier
|
||||
at time.Time
|
||||
invitationWindow time.Duration
|
||||
invitationLimit int64
|
||||
cardViewWindow time.Duration
|
||||
cardViewLimit int64
|
||||
}
|
||||
|
||||
// NewCompanyQuota resolves the organization's trusted verification against
|
||||
// an effective product policy. at is the application clock snapshot for the
|
||||
// whole operation; a request from before the organization or its current
|
||||
// verification record is rejected so a stale timestamp cannot use older
|
||||
// trust.
|
||||
func NewCompanyQuota(organization Organization, version PolicyVersion, at time.Time) (CompanyQuota, error) {
|
||||
const location = "domain.NewCompanyQuota"
|
||||
if organization.IsZero() {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - organization must be restored from trusted storage: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if version.IsZero() || version.Key() != ProductPolicyKey {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - an effective product policy is required: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if at.IsZero() || at.Unix() < 0 {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - application time must be set and non-negative: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
at = at.UTC()
|
||||
verification := organization.Verification()
|
||||
if at.Before(organization.CreatedAt()) || at.Before(verification.ChangedAt()) {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - application time predates organization trust: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if version.EffectiveAt().After(at) {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - policy is not effective at application time: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
|
||||
tier, ok := verification.Level().QuotaTier()
|
||||
if !ok {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - verification level has no quota tier: %w", location, ErrCompanyQuotaDenied)
|
||||
}
|
||||
policy := version.Policy().OrganizationQuotas
|
||||
tierPolicy, err := policy.Tier(tier)
|
||||
if err != nil {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - read the organization tier: %w", location, err)
|
||||
}
|
||||
if !tierPolicy.Active {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - organization tier is not active: %w", location, ErrCompanyQuotaDenied)
|
||||
}
|
||||
|
||||
return CompanyQuota{
|
||||
organizationID: organization.ID(),
|
||||
policyVersionID: version.ID(),
|
||||
verificationLevel: verification.Level(),
|
||||
verificationBasis: verification.Basis(),
|
||||
verificationChanged: verification.ChangedAt().UTC(),
|
||||
tier: tier,
|
||||
at: at,
|
||||
invitationWindow: policy.InvitationWindow.Duration(),
|
||||
invitationLimit: int64(tierPolicy.InvitationsPerWindow),
|
||||
cardViewWindow: policy.CardViewWindow.Duration(),
|
||||
cardViewLimit: int64(tierPolicy.DistinctCardViewsPerWindow),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) OrganizationID() uuid.UUID { return quota.organizationID }
|
||||
|
||||
func (quota CompanyQuota) PolicyVersionID() PolicyVersionID { return quota.policyVersionID }
|
||||
|
||||
func (quota CompanyQuota) VerificationLevel() OrganizationVerificationLevel {
|
||||
return quota.verificationLevel
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) VerificationBasis() OrganizationVerificationBasis {
|
||||
return quota.verificationBasis
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) VerificationChangedAt() time.Time { return quota.verificationChanged }
|
||||
|
||||
func (quota CompanyQuota) Tier() OrganizationTier { return quota.tier }
|
||||
|
||||
func (quota CompanyQuota) At() time.Time { return quota.at }
|
||||
|
||||
func (quota CompanyQuota) InvitationWindow() time.Duration { return quota.invitationWindow }
|
||||
|
||||
func (quota CompanyQuota) InvitationWindowStart() time.Time {
|
||||
if quota.invitationWindow <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return quota.at.Add(-quota.invitationWindow)
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) InvitationLimit() int64 { return quota.invitationLimit }
|
||||
|
||||
func (quota CompanyQuota) CardViewWindow() time.Duration { return quota.cardViewWindow }
|
||||
|
||||
func (quota CompanyQuota) CardViewWindowStart() time.Time {
|
||||
if quota.cardViewWindow <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return quota.at.Add(-quota.cardViewWindow)
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) CardViewLimit() int64 { return quota.cardViewLimit }
|
||||
|
||||
// IsZero reports a snapshot that was not built by NewCompanyQuota.
|
||||
func (quota CompanyQuota) IsZero() bool { return quota.organizationID == uuid.Nil }
|
||||
@@ -0,0 +1,146 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestNewCompanyQuotaUsesStoredVerificationAndEffectivePolicy(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
|
||||
createdAt := at.Add(-30 * 24 * time.Hour).UTC()
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), createdAt, createdAt)
|
||||
policy := companyQuotaTestPolicy(t, at.UTC().Add(-time.Hour), false)
|
||||
|
||||
quota, err := NewCompanyQuota(organization, policy, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota() error = %v", err)
|
||||
}
|
||||
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() ||
|
||||
quota.Tier() != OrganizationTierE0 || quota.VerificationLevel() != OrganizationVerificationE0 ||
|
||||
quota.VerificationBasis() != OrganizationBasisConfirmedEmail || !quota.VerificationChangedAt().Equal(createdAt) {
|
||||
t.Fatalf("quota identity = org %s, policy %s, tier %s, verification %s/%s at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.VerificationLevel(), quota.VerificationBasis(), quota.VerificationChangedAt())
|
||||
}
|
||||
if !quota.At().Equal(at.UTC()) || quota.At().Location() != time.UTC {
|
||||
t.Fatalf("At() = %s, want %s in UTC", quota.At(), at.UTC())
|
||||
}
|
||||
if quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 ||
|
||||
quota.InvitationWindow() != 7*24*time.Hour || quota.CardViewWindow() != 24*time.Hour {
|
||||
t.Fatalf("quota limits/windows = %d/%s and %d/%s", quota.InvitationLimit(), quota.InvitationWindow(), quota.CardViewLimit(), quota.CardViewWindow())
|
||||
}
|
||||
if want := at.UTC().Add(-7 * 24 * time.Hour); !quota.InvitationWindowStart().Equal(want) {
|
||||
t.Fatalf("InvitationWindowStart() = %s, want %s", quota.InvitationWindowStart(), want)
|
||||
}
|
||||
if want := at.UTC().Add(-24 * time.Hour); !quota.CardViewWindowStart().Equal(want) {
|
||||
t.Fatalf("CardViewWindowStart() = %s, want %s", quota.CardViewWindowStart(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaRequiresBothStoredE2VerificationAndActivePolicyTier(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE2), string(OrganizationBasisRequisitesAndAuthority), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
|
||||
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), false), at); !errors.Is(err, ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("NewCompanyQuota(E2, inactive policy tier) error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
|
||||
quota, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota(E2, active policy tier) error = %v", err)
|
||||
}
|
||||
if quota.Tier() != OrganizationTierE2 || quota.InvitationLimit() != 100 || quota.CardViewLimit() != 400 {
|
||||
t.Fatalf("E2 quota = tier %s, limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaDeniesE3WithoutFallingBackToE0(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE3), string(OrganizationBasisManualReview), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
|
||||
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at); !errors.Is(err, ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("NewCompanyQuota(E3) error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaRejectsUntrustedOrBackdatedInputs(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
policy := companyQuotaTestPolicy(t, at.Add(-time.Hour), false)
|
||||
futurePolicy := companyQuotaTestPolicy(t, at.Add(time.Hour), false)
|
||||
beforeEpoch := time.Date(1969, 12, 31, 23, 59, 59, 0, time.UTC)
|
||||
createdInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(time.Hour), at.Add(time.Hour))
|
||||
verifiedInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE1), string(OrganizationBasisCorporateDomain), at.Add(-time.Hour), at.Add(time.Hour))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
organization Organization
|
||||
policy PolicyVersion
|
||||
at time.Time
|
||||
want error
|
||||
}{
|
||||
{name: "zero organization", organization: Organization{}, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "zero policy", organization: organization, policy: PolicyVersion{}, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "zero application time", organization: organization, policy: policy, want: ErrInvalidCompanyQuota},
|
||||
{name: "negative application time", organization: organization, policy: policy, at: beforeEpoch, want: ErrInvalidCompanyQuota},
|
||||
{name: "organization created after request time", organization: createdInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "verification changed after request time", organization: verifiedInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "policy effective after request time", organization: organization, policy: futurePolicy, at: at, want: ErrInvalidCompanyQuota},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := NewCompanyQuota(test.organization, test.policy, test.at); !errors.Is(err, test.want) {
|
||||
t.Fatalf("NewCompanyQuota() error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func companyQuotaTestOrganization(t *testing.T, level, basis string, createdAt, changedAt time.Time) Organization {
|
||||
t.Helper()
|
||||
updatedAt := createdAt
|
||||
if changedAt.After(updatedAt) {
|
||||
updatedAt = changedAt
|
||||
}
|
||||
organization, err := RestoreOrganization(StoredOrganization{
|
||||
ID: uuid.New(),
|
||||
Name: "Example Company",
|
||||
VerificationLevel: level,
|
||||
VerificationBasis: basis,
|
||||
VerificationChangedAt: changedAt,
|
||||
Version: 1,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreOrganization() error = %v", err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
func companyQuotaTestPolicy(t *testing.T, effectiveAt time.Time, activateE2 bool) PolicyVersion {
|
||||
t.Helper()
|
||||
policy := DemoProductPolicyV1()
|
||||
policy.OrganizationQuotas.TierE2.Active = activateE2
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(1)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash := numbered.DocumentHash()
|
||||
version, err := RestorePolicyVersion(StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
|
||||
Author: string(numbered.Author()), EffectiveAt: effectiveAt, CreatedAt: effectiveAt,
|
||||
Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidCandidateQuestionnaire reports a questionnaire value that
|
||||
// breaks its contract or cannot be restored from storage.
|
||||
ErrInvalidCandidateQuestionnaire = errors.New("invalid candidate questionnaire")
|
||||
|
||||
// ErrCandidateQuestionnaireVersionConflict reports that the saved
|
||||
// questionnaire changed after the caller read it.
|
||||
ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
|
||||
)
|
||||
|
||||
const (
|
||||
maxQuestionnaireSpecializations = 2
|
||||
maxQuestionnaireTaskLanguages = 2
|
||||
maxQuestionnaireStackItems = 20
|
||||
maxQuestionnaireStackTagRunes = 50
|
||||
maxQuestionnaireExperienceMonth = 600
|
||||
)
|
||||
|
||||
const redactedQuestionnaire = "[redacted candidate questionnaire]"
|
||||
|
||||
// CandidateQuestionnaireFieldError describes one invalid request field. The
|
||||
// reason is fixed text and never includes the submitted value.
|
||||
type CandidateQuestionnaireFieldError struct {
|
||||
Pointer string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (fieldError *CandidateQuestionnaireFieldError) Error() string {
|
||||
return "candidate questionnaire field " + fieldError.Pointer + " " + fieldError.Reason
|
||||
}
|
||||
|
||||
func (fieldError *CandidateQuestionnaireFieldError) Unwrap() error {
|
||||
return ErrInvalidCandidateQuestionnaire
|
||||
}
|
||||
|
||||
func invalidQuestionnaireField(location, pointer, reason string) error {
|
||||
return fmt.Errorf("%s - %w", location, &CandidateQuestionnaireFieldError{Pointer: pointer, Reason: reason})
|
||||
}
|
||||
|
||||
// TaskLanguageCode identifies a language actually offered by a published
|
||||
// assessment bank. The catalog projection, not this enum, decides which one
|
||||
// is currently valid for a specialization.
|
||||
type TaskLanguageCode string
|
||||
|
||||
const (
|
||||
TaskLanguagePython TaskLanguageCode = "python"
|
||||
TaskLanguageGo TaskLanguageCode = "go"
|
||||
)
|
||||
|
||||
func (language TaskLanguageCode) IsKnown() bool {
|
||||
return language == TaskLanguagePython || language == TaskLanguageGo
|
||||
}
|
||||
|
||||
// QuestionnaireWorkFormat is an acceptable work format.
|
||||
type QuestionnaireWorkFormat string
|
||||
|
||||
const (
|
||||
QuestionnaireWorkFormatRemote QuestionnaireWorkFormat = "remote"
|
||||
QuestionnaireWorkFormatOffice QuestionnaireWorkFormat = "office"
|
||||
QuestionnaireWorkFormatHybrid QuestionnaireWorkFormat = "hybrid"
|
||||
)
|
||||
|
||||
func (format QuestionnaireWorkFormat) IsKnown() bool {
|
||||
switch format {
|
||||
case QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatOffice, QuestionnaireWorkFormatHybrid:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// QuestionnaireExperience contains self-reported month totals. It does not
|
||||
// contribute assessment points and has no field for a confirmed grade.
|
||||
type QuestionnaireExperience struct {
|
||||
CommercialMonths int32
|
||||
AcademicMonths int32
|
||||
}
|
||||
|
||||
func (QuestionnaireExperience) String() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireExperience) GoString() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireExperience) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (QuestionnaireExperience) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// QuestionnaireSpecialization is one self-assessed specialization. Its grade
|
||||
// is a candidate claim, never a confirmed grade or category.
|
||||
type QuestionnaireSpecialization struct {
|
||||
Specialization SpecializationCode
|
||||
SelfAssessedGrade GradeCode
|
||||
TaskLanguages []TaskLanguageCode
|
||||
Stack []string
|
||||
Experience *QuestionnaireExperience
|
||||
}
|
||||
|
||||
func (QuestionnaireSpecialization) String() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireSpecialization) GoString() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireSpecialization) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (QuestionnaireSpecialization) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// CandidateQuestionnaireInput is the complete replacement sent by a
|
||||
// candidate. It contains personal data and must not be logged.
|
||||
type CandidateQuestionnaireInput struct {
|
||||
Specializations []QuestionnaireSpecialization
|
||||
WorkFormats []QuestionnaireWorkFormat
|
||||
}
|
||||
|
||||
func (CandidateQuestionnaireInput) String() string { return redactedQuestionnaire }
|
||||
func (CandidateQuestionnaireInput) GoString() string { return redactedQuestionnaire }
|
||||
func (CandidateQuestionnaireInput) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (CandidateQuestionnaireInput) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// SpecializationAvailability is the current published-bank projection shared
|
||||
// by the public catalog and questionnaire validation. Empty grades and
|
||||
// languages mean that the specialization is not currently available.
|
||||
type SpecializationAvailability struct {
|
||||
Specialization SpecializationCode
|
||||
Grades []GradeCode
|
||||
TaskLanguages []TaskLanguageCode
|
||||
}
|
||||
|
||||
// CandidateQuestionnaire is the private questionnaire of one candidate.
|
||||
// Version zero means no questionnaire has been saved yet.
|
||||
type CandidateQuestionnaire struct {
|
||||
userID uuid.UUID
|
||||
version int64
|
||||
specializations []QuestionnaireSpecialization
|
||||
workFormats []QuestionnaireWorkFormat
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
// EmptyCandidateQuestionnaire returns the unsaved questionnaire of userID.
|
||||
func EmptyCandidateQuestionnaire(userID uuid.UUID) (CandidateQuestionnaire, error) {
|
||||
if userID == uuid.Nil {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("domain.EmptyCandidateQuestionnaire - user ID must not be nil: %w", ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
return CandidateQuestionnaire{userID: userID}, nil
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) UserID() uuid.UUID { return questionnaire.userID }
|
||||
func (questionnaire CandidateQuestionnaire) Version() int64 { return questionnaire.version }
|
||||
func (questionnaire CandidateQuestionnaire) CreatedAt() time.Time {
|
||||
return questionnaire.createdAt
|
||||
}
|
||||
func (questionnaire CandidateQuestionnaire) UpdatedAt() time.Time {
|
||||
return questionnaire.updatedAt
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) Specializations() []QuestionnaireSpecialization {
|
||||
return cloneQuestionnaireSpecializations(questionnaire.specializations)
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) WorkFormats() []QuestionnaireWorkFormat {
|
||||
return slices.Clone(questionnaire.workFormats)
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) IsZero() bool { return questionnaire.userID == uuid.Nil }
|
||||
|
||||
// SameContent reports whether two questionnaires for the same candidate have
|
||||
// identical validated answers, without comparing versions or timestamps.
|
||||
func (questionnaire CandidateQuestionnaire) SameContent(other CandidateQuestionnaire) bool {
|
||||
return !questionnaire.IsZero() && questionnaire.userID == other.userID &&
|
||||
equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, questionnaireContent{
|
||||
specializations: other.specializations,
|
||||
workFormats: other.workFormats,
|
||||
})
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) String() string { return redactedQuestionnaire }
|
||||
func (questionnaire CandidateQuestionnaire) GoString() string { return redactedQuestionnaire }
|
||||
func (questionnaire CandidateQuestionnaire) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (questionnaire CandidateQuestionnaire) LogValue() slog.Value {
|
||||
return slog.GroupValue(
|
||||
slog.String("user_id", questionnaire.userID.String()),
|
||||
slog.Int64("version", questionnaire.version),
|
||||
)
|
||||
}
|
||||
|
||||
// StoredCandidateQuestionnaire is the database projection used to restore a
|
||||
// saved questionnaire. A missing row is represented by EmptyCandidateQuestionnaire.
|
||||
type StoredCandidateQuestionnaire struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
Specializations []QuestionnaireSpecialization
|
||||
WorkFormats []QuestionnaireWorkFormat
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// RestoreCandidateQuestionnaire validates a saved questionnaire before it is
|
||||
// exposed to a usecase. Current bank availability is intentionally not part
|
||||
// of restoration; a later bank change must not make saved answers unreadable.
|
||||
func RestoreCandidateQuestionnaire(stored StoredCandidateQuestionnaire) (CandidateQuestionnaire, error) {
|
||||
const location = "domain.RestoreCandidateQuestionnaire"
|
||||
if stored.UserID == uuid.Nil || stored.Version < 1 || stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt) {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("%s - stored identity, version, or time is invalid: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
content, err := validateQuestionnaireInput(CandidateQuestionnaireInput{
|
||||
Specializations: stored.Specializations,
|
||||
WorkFormats: stored.WorkFormats,
|
||||
}, location)
|
||||
if err != nil {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("%s - validate stored content: %w", location, err)
|
||||
}
|
||||
return CandidateQuestionnaire{
|
||||
userID: stored.UserID, version: stored.Version,
|
||||
specializations: content.specializations, workFormats: content.workFormats,
|
||||
createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Replace validates a complete replacement and reports whether it changes
|
||||
// the current questionnaire. Identical retries are no-ops even with an older
|
||||
// expected version; a changed stale request conflicts.
|
||||
func (questionnaire CandidateQuestionnaire) Replace(
|
||||
input CandidateQuestionnaireInput,
|
||||
expectedVersion int64,
|
||||
at time.Time,
|
||||
availability []SpecializationAvailability,
|
||||
) (CandidateQuestionnaire, bool, error) {
|
||||
const location = "CandidateQuestionnaire.Replace"
|
||||
if questionnaire.IsZero() {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - questionnaire was not built by EmptyCandidateQuestionnaire or RestoreCandidateQuestionnaire: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateQuestionnaireVersionConflict)
|
||||
if expectedVersion < 0 || expectedVersion > questionnaire.version {
|
||||
return CandidateQuestionnaire{}, false, conflict
|
||||
}
|
||||
if at.IsZero() {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
content, err := validateQuestionnaireInput(input, location)
|
||||
if err != nil {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - validate content: %w", location, err)
|
||||
}
|
||||
if equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, content) {
|
||||
return questionnaire, false, nil
|
||||
}
|
||||
if expectedVersion != questionnaire.version {
|
||||
return CandidateQuestionnaire{}, false, conflict
|
||||
}
|
||||
if err := validateQuestionnaireTaskLanguages(content.specializations, availability, location); err != nil {
|
||||
return CandidateQuestionnaire{}, false, err
|
||||
}
|
||||
updated := questionnaire
|
||||
updated.specializations = content.specializations
|
||||
updated.workFormats = content.workFormats
|
||||
updated.updatedAt = at
|
||||
if at.Before(questionnaire.updatedAt) {
|
||||
updated.updatedAt = questionnaire.updatedAt
|
||||
}
|
||||
if updated.createdAt.IsZero() {
|
||||
updated.createdAt = updated.updatedAt
|
||||
}
|
||||
return updated, true, nil
|
||||
}
|
||||
|
||||
type questionnaireContent struct {
|
||||
specializations []QuestionnaireSpecialization
|
||||
workFormats []QuestionnaireWorkFormat
|
||||
}
|
||||
|
||||
func validateQuestionnaireInput(input CandidateQuestionnaireInput, location string) (questionnaireContent, error) {
|
||||
if len(input.Specializations) < 1 || len(input.Specializations) > maxQuestionnaireSpecializations {
|
||||
return questionnaireContent{}, invalidQuestionnaireField(location, "/specializations", "must contain one or two items")
|
||||
}
|
||||
if len(input.WorkFormats) < 1 || len(input.WorkFormats) > 3 {
|
||||
return questionnaireContent{}, invalidQuestionnaireField(location, "/work_context/work_formats", "must contain one to three items")
|
||||
}
|
||||
content := questionnaireContent{
|
||||
specializations: make([]QuestionnaireSpecialization, 0, len(input.Specializations)),
|
||||
workFormats: slices.Clone(input.WorkFormats),
|
||||
}
|
||||
var err error
|
||||
content.specializations, err = validateQuestionnaireSpecializations(input.Specializations, location)
|
||||
if err != nil {
|
||||
return questionnaireContent{}, err
|
||||
}
|
||||
if err := validateQuestionnaireWorkFormats(content.workFormats, location); err != nil {
|
||||
return questionnaireContent{}, err
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireSpecializations(
|
||||
answers []QuestionnaireSpecialization,
|
||||
location string,
|
||||
) ([]QuestionnaireSpecialization, error) {
|
||||
validated := make([]QuestionnaireSpecialization, 0, len(answers))
|
||||
seenSpecializations := make(map[SpecializationCode]struct{}, len(answers))
|
||||
for index, answer := range answers {
|
||||
pointer := fmt.Sprintf("/specializations/%d", index)
|
||||
if !answer.Specialization.IsKnown() {
|
||||
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must be a specialization of the catalog")
|
||||
}
|
||||
if _, exists := seenSpecializations[answer.Specialization]; exists {
|
||||
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must not repeat an earlier item")
|
||||
}
|
||||
seenSpecializations[answer.Specialization] = struct{}{}
|
||||
validatedAnswer, err := validateQuestionnaireSpecialization(answer, pointer, location)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
validated = append(validated, validatedAnswer)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireSpecialization(
|
||||
answer QuestionnaireSpecialization,
|
||||
pointer, location string,
|
||||
) (QuestionnaireSpecialization, error) {
|
||||
if !answer.SelfAssessedGrade.IsKnown() {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/self_assessed_grade", "must be a grade of the catalog")
|
||||
}
|
||||
if len(answer.TaskLanguages) > maxQuestionnaireTaskLanguages {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/task_languages", "must have at most two items")
|
||||
}
|
||||
if len(answer.Stack) > maxQuestionnaireStackItems {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/stack", "must have at most twenty items")
|
||||
}
|
||||
answer.TaskLanguages = slices.Clone(answer.TaskLanguages)
|
||||
if err := validateQuestionnaireTaskLanguageInputs(answer.TaskLanguages, pointer, location); err != nil {
|
||||
return QuestionnaireSpecialization{}, err
|
||||
}
|
||||
answer.Stack = slices.Clone(answer.Stack)
|
||||
if err := validateQuestionnaireStack(answer.Stack, pointer, location); err != nil {
|
||||
return QuestionnaireSpecialization{}, err
|
||||
}
|
||||
if answer.Experience != nil {
|
||||
experience := *answer.Experience
|
||||
if experience.CommercialMonths < 0 || experience.CommercialMonths > maxQuestionnaireExperienceMonth {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/commercial_months", "must be between zero and 600")
|
||||
}
|
||||
if experience.AcademicMonths < 0 || experience.AcademicMonths > maxQuestionnaireExperienceMonth {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/academic_months", "must be between zero and 600")
|
||||
}
|
||||
answer.Experience = &experience
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireTaskLanguageInputs(languages []TaskLanguageCode, pointer, location string) error {
|
||||
seen := make(map[TaskLanguageCode]struct{}, len(languages))
|
||||
for index, language := range languages {
|
||||
languagePointer := fmt.Sprintf("%s/task_languages/%d", pointer, index)
|
||||
if !language.IsKnown() {
|
||||
return invalidQuestionnaireField(location, languagePointer, "must be a task language of the catalog")
|
||||
}
|
||||
if _, exists := seen[language]; exists {
|
||||
return invalidQuestionnaireField(location, languagePointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[language] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireStack(tags []string, pointer, location string) error {
|
||||
seen := make(map[string]struct{}, len(tags))
|
||||
for index, tag := range tags {
|
||||
tagPointer := fmt.Sprintf("%s/stack/%d", pointer, index)
|
||||
if reason := singleLineTextProblem(tag, maxQuestionnaireStackTagRunes); reason != "" {
|
||||
return invalidQuestionnaireField(location, tagPointer, reason)
|
||||
}
|
||||
key := strings.ToLower(tag)
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidQuestionnaireField(location, tagPointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireWorkFormats(formats []QuestionnaireWorkFormat, location string) error {
|
||||
seen := make(map[QuestionnaireWorkFormat]struct{}, len(formats))
|
||||
for index, format := range formats {
|
||||
pointer := fmt.Sprintf("/work_context/work_formats/%d", index)
|
||||
if !format.IsKnown() {
|
||||
return invalidQuestionnaireField(location, pointer, "must be remote, office, or hybrid")
|
||||
}
|
||||
if _, exists := seen[format]; exists {
|
||||
return invalidQuestionnaireField(location, pointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[format] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireTaskLanguages(
|
||||
answers []QuestionnaireSpecialization,
|
||||
availability []SpecializationAvailability,
|
||||
location string,
|
||||
) error {
|
||||
allowed := make(map[SpecializationCode]map[TaskLanguageCode]struct{}, len(availability))
|
||||
for _, item := range availability {
|
||||
if !item.Specialization.IsKnown() {
|
||||
return fmt.Errorf("%s - availability contains an unknown specialization: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
languages := make(map[TaskLanguageCode]struct{}, len(item.TaskLanguages))
|
||||
for _, language := range item.TaskLanguages {
|
||||
if !language.IsKnown() {
|
||||
return fmt.Errorf("%s - availability contains an unknown task language: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
languages[language] = struct{}{}
|
||||
}
|
||||
allowed[item.Specialization] = languages
|
||||
}
|
||||
for specializationIndex, answer := range answers {
|
||||
for languageIndex, language := range answer.TaskLanguages {
|
||||
if _, exists := allowed[answer.Specialization][language]; !exists {
|
||||
pointer := fmt.Sprintf("/specializations/%d/task_languages/%d", specializationIndex, languageIndex)
|
||||
return invalidQuestionnaireField(location, pointer, "must be offered by the current published bank for this specialization")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func equalQuestionnaireContent(
|
||||
leftSpecializations []QuestionnaireSpecialization,
|
||||
leftFormats []QuestionnaireWorkFormat,
|
||||
right questionnaireContent,
|
||||
) bool {
|
||||
if !slices.Equal(leftFormats, right.workFormats) || len(leftSpecializations) != len(right.specializations) {
|
||||
return false
|
||||
}
|
||||
for index, left := range leftSpecializations {
|
||||
right := right.specializations[index]
|
||||
if left.Specialization != right.Specialization || left.SelfAssessedGrade != right.SelfAssessedGrade ||
|
||||
!slices.Equal(left.TaskLanguages, right.TaskLanguages) || !slices.Equal(left.Stack, right.Stack) ||
|
||||
!equalQuestionnaireExperience(left.Experience, right.Experience) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func equalQuestionnaireExperience(left, right *QuestionnaireExperience) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func cloneQuestionnaireSpecializations(items []QuestionnaireSpecialization) []QuestionnaireSpecialization {
|
||||
if items == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := make([]QuestionnaireSpecialization, len(items))
|
||||
for index, item := range items {
|
||||
cloned[index] = item
|
||||
cloned[index].TaskLanguages = slices.Clone(item.TaskLanguages)
|
||||
cloned[index].Stack = slices.Clone(item.Stack)
|
||||
if item.Experience != nil {
|
||||
experience := *item.Experience
|
||||
cloned[index].Experience = &experience
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCandidateQuestionnaireReplaceValidatesCurrentTaskLanguages(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(id)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
input := validQuestionnaireInput()
|
||||
availability := []SpecializationAvailability{{
|
||||
Specialization: SpecializationBackend,
|
||||
Grades: []GradeCode{GradeJunior},
|
||||
TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
|
||||
}}
|
||||
updated, changed, err := questionnaire.Replace(input, 0, now, availability)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("Replace(valid) = changed %v, error %v; want changed", changed, err)
|
||||
}
|
||||
if updated.Version() != 0 || !updated.CreatedAt().Equal(now) || !updated.UpdatedAt().Equal(now) {
|
||||
t.Fatalf("updated version/times = %d %s %s, want version 0 and application time", updated.Version(), updated.CreatedAt(), updated.UpdatedAt())
|
||||
}
|
||||
if got := updated.Specializations()[0].SelfAssessedGrade; got != GradeJunior {
|
||||
t.Fatalf("self-assessed grade = %q, want junior", got)
|
||||
}
|
||||
|
||||
badInput := validQuestionnaireInput()
|
||||
badInput.Specializations[0].TaskLanguages = []TaskLanguageCode{TaskLanguagePython}
|
||||
_, _, err = questionnaire.Replace(badInput, 0, now, availability)
|
||||
if !errors.Is(err, ErrInvalidCandidateQuestionnaire) {
|
||||
t.Fatalf("Replace(unoffered language) error = %v, want invalid questionnaire", err)
|
||||
}
|
||||
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" || strings.Contains(err.Error(), "python") {
|
||||
t.Fatalf("unoffered language error = %v, want fixed field error without submitted value", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireAllowsInDevelopmentSpecializationWithoutLanguages(t *testing.T) {
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := validQuestionnaireInput()
|
||||
input.Specializations[0].Specialization = SpecializationDSML
|
||||
input.Specializations[0].TaskLanguages = nil
|
||||
_, changed, err := questionnaire.Replace(input, 0, time.Now().UTC(), nil)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("Replace(in-development specialization) = changed %v, error %v; want success with empty languages", changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireNoOpAndVersionConflict(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
stored, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 2, Specializations: validQuestionnaireInput().Specializations,
|
||||
WorkFormats: validQuestionnaireInput().WorkFormats, CreatedAt: now, UpdatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
input := validQuestionnaireInput()
|
||||
noOp, changed, err := stored.Replace(input, 1, now.Add(time.Hour), nil)
|
||||
if err != nil || changed || noOp.Version() != 2 || !noOp.UpdatedAt().Equal(now) {
|
||||
t.Fatalf("Replace(stale no-op) = changed %v, version %d, time %s, error %v; want unchanged version 2", changed, noOp.Version(), noOp.UpdatedAt(), err)
|
||||
}
|
||||
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatOffice}
|
||||
_, _, err = stored.Replace(input, 1, now.Add(time.Hour), nil)
|
||||
if !errors.Is(err, ErrCandidateQuestionnaireVersionConflict) {
|
||||
t.Fatalf("Replace(stale changed) error = %v, want version conflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireSameContentIgnoresVersionAndTimes(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
input := validQuestionnaireInput()
|
||||
firstAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
first, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 2, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: firstAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(first) error = %v", err)
|
||||
}
|
||||
secondAt := firstAt.Add(time.Hour)
|
||||
second, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 3, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(second) error = %v", err)
|
||||
}
|
||||
if !first.SameContent(second) || !second.SameContent(first) {
|
||||
t.Fatal("SameContent() must ignore version and timestamps but require the same user")
|
||||
}
|
||||
|
||||
otherUser, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: uuid.Must(uuid.NewV7()), Version: 3, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(other user) error = %v", err)
|
||||
}
|
||||
if first.SameContent(otherUser) {
|
||||
t.Fatal("SameContent() treated another user's questionnaire as identical")
|
||||
}
|
||||
|
||||
changedInput := input
|
||||
changedInput.Specializations = slices.Clone(input.Specializations)
|
||||
changedInput.Specializations[0].Stack = []string{"gRPC"}
|
||||
changed, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 3, Specializations: changedInput.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(changed) error = %v", err)
|
||||
}
|
||||
if first.SameContent(changed) {
|
||||
t.Fatal("SameContent() ignored a changed answer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireRejectsDuplicateAndMalformedValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*CandidateQuestionnaireInput)
|
||||
pointer string
|
||||
}{
|
||||
{
|
||||
name: "repeated specialization",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations = append(input.Specializations, input.Specializations[0])
|
||||
},
|
||||
pointer: "/specializations/1/specialization",
|
||||
},
|
||||
{
|
||||
name: "case insensitive stack duplicate",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations[0].Stack = []string{"PostgreSQL", "postgresql"}
|
||||
},
|
||||
pointer: "/specializations/0/stack/1",
|
||||
},
|
||||
{
|
||||
name: "experience above bound",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations[0].Experience = &QuestionnaireExperience{CommercialMonths: 601}
|
||||
},
|
||||
pointer: "/specializations/0/experience/commercial_months",
|
||||
},
|
||||
{
|
||||
name: "duplicate work format",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatRemote}
|
||||
},
|
||||
pointer: "/work_context/work_formats/1",
|
||||
},
|
||||
}
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := validQuestionnaireInput()
|
||||
test.mutate(&input)
|
||||
_, _, err := questionnaire.Replace(input, 0, time.Now().UTC(), []SpecializationAvailability{{
|
||||
Specialization: SpecializationBackend, TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
|
||||
}})
|
||||
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != test.pointer {
|
||||
t.Fatalf("Replace() error = %v, want field pointer %s", err, test.pointer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireCopiesSensitiveCollectionsAndRedacts(t *testing.T) {
|
||||
input := validQuestionnaireInput()
|
||||
questionnaire, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: uuid.Must(uuid.NewV7()), Version: 1, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
items := questionnaire.Specializations()
|
||||
items[0].Stack[0] = "changed"
|
||||
items[0].Experience.CommercialMonths = 0
|
||||
if questionnaire.Specializations()[0].Stack[0] != "PostgreSQL" || questionnaire.Specializations()[0].Experience.CommercialMonths != 12 {
|
||||
t.Fatal("Specializations() exposed mutable internal data")
|
||||
}
|
||||
for _, formatted := range []string{fmt.Sprint(questionnaire), fmt.Sprintf("%+v", input.Specializations[0]), fmt.Sprint(input)} {
|
||||
if strings.Contains(formatted, "PostgreSQL") || strings.Contains(formatted, "12") {
|
||||
t.Fatalf("formatted questionnaire data leaked personal values: %s", formatted)
|
||||
}
|
||||
}
|
||||
for _, typ := range []reflect.Type{
|
||||
reflect.TypeFor[CandidateQuestionnaire](),
|
||||
reflect.TypeFor[QuestionnaireSpecialization](),
|
||||
} {
|
||||
for index := range typ.NumField() {
|
||||
name := strings.ToLower(typ.Field(index).Name)
|
||||
if strings.Contains(name, "confirmed") || name == "category" {
|
||||
t.Errorf("%s has forbidden field %q", typ.Name(), typ.Field(index).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validQuestionnaireInput() CandidateQuestionnaireInput {
|
||||
return CandidateQuestionnaireInput{
|
||||
Specializations: []QuestionnaireSpecialization{{
|
||||
Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior,
|
||||
TaskLanguages: []TaskLanguageCode{TaskLanguageGo}, Stack: []string{"PostgreSQL"},
|
||||
Experience: &QuestionnaireExperience{CommercialMonths: 12, AcademicMonths: 4},
|
||||
}},
|
||||
WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote},
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,10 @@ var (
|
||||
|
||||
// ErrAssessmentCategoryNotOpen reports that the category has no opening.
|
||||
ErrAssessmentCategoryNotOpen = errors.New("assessment category is not open")
|
||||
|
||||
// ErrAssessmentCatalogBindingImmutable reports an attempt to edit or remove
|
||||
// an immutable reviewed catalog binding.
|
||||
ErrAssessmentCatalogBindingImmutable = errors.New("assessment catalog binding is immutable")
|
||||
)
|
||||
|
||||
// MaxAssessmentFamilyPageSize is the largest page that ListFamilies returns.
|
||||
@@ -126,6 +130,15 @@ type AssessmentBankRepository interface {
|
||||
// the draft's own numbers are not stored.
|
||||
CreateCategoryOpening(ctx context.Context, draft domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error)
|
||||
|
||||
// BindCategoryCatalog attaches reviewed public metadata to an opening. The
|
||||
// adapter pins it to the exact currently published family manifest.
|
||||
BindCategoryCatalog(ctx context.Context, opening domain.AssessmentCategoryOpening, metadata domain.AssessmentCategoryCatalogMetadata) error
|
||||
|
||||
// ListCurrentSpecializationAvailability returns ready public specializations
|
||||
// from one database snapshot. Legacy openings or bindings whose policy,
|
||||
// coverage, or published-family manifest changed are omitted.
|
||||
ListCurrentSpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, 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.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var ErrCompanyQuotaSnapshotChanged = errors.New("company quota snapshot changed")
|
||||
|
||||
// CompanyQuotaDecision is the result of an atomic invitation or card-view
|
||||
// reservation. Reused means the same invitation or a recent view already
|
||||
// counted, so it is allowed without another usage charge. A denied decision
|
||||
// has Reused false and RetryAt set to the earliest expiry that can free room,
|
||||
// in UTC.
|
||||
type CompanyQuotaDecision struct {
|
||||
Allowed bool
|
||||
Reused bool
|
||||
RetryAt time.Time
|
||||
}
|
||||
|
||||
// CompanyQuotaRepository atomically reserves per-organization invitation and
|
||||
// candidate-card usage. Implementations are transaction-bound: a caller
|
||||
// creates the invitation or applies the visibility change in the same
|
||||
// transaction, so a failed business operation cannot leave quota charged.
|
||||
//
|
||||
// Writers lock rows in this order: organization, active membership,
|
||||
// invitation or visibility record, then quota usage. A repository may take an
|
||||
// organization lock again inside the same transaction, but must not invert
|
||||
// this order. Each method rechecks the organization's stored verification
|
||||
// level, basis, and changed_at against the snapshot in CompanyQuota before it
|
||||
// writes; a caller cannot grant itself a tier by supplying a different level.
|
||||
//
|
||||
// Invitation usage is keyed by organization and invitation ID and remains
|
||||
// until the organization is deleted. The unique key makes retries idempotent
|
||||
// even when they arrive with a different request idempotency key; pruning by
|
||||
// the rolling quota window would allow an old invitation to count again.
|
||||
// Card-view usage is keyed by organization and candidate, counts only when
|
||||
// last_seen is strictly after the rolling-window cutoff, and expires
|
||||
// logically at that boundary. Bounded cleanup is opportunistic after a
|
||||
// successful reservation, so physical row removal has no exact-time promise.
|
||||
// Repeated views update last_seen monotonically with the greater of the
|
||||
// stored and current times.
|
||||
type CompanyQuotaRepository interface {
|
||||
// ReserveInvitation counts a new invitation against the current policy
|
||||
// limit. An existing invitation ID is returned as allowed and reused
|
||||
// without a second charge, regardless of its age or the request key. A
|
||||
// denied new invitation writes no usage and reports RetryAt after the
|
||||
// earliest currently counted invitation expires.
|
||||
ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error)
|
||||
|
||||
// ReserveCardView counts a distinct candidate within the rolling card-view
|
||||
// window. A repeat while the prior view is active is allowed and reused,
|
||||
// and refreshes last_seen with a monotonic update. A denied new view writes
|
||||
// no usage and reports RetryAt after the earliest active view expires.
|
||||
ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
|
||||
|
||||
// CandidateQuestionnaireRepositories exposes the questionnaire repository
|
||||
// bound to a UnitOfWork transaction.
|
||||
type CandidateQuestionnaireRepositories interface {
|
||||
CandidateQuestionnaires() CandidateQuestionnaireRepository
|
||||
}
|
||||
|
||||
// CandidateQuestionnaireRepository reads and replaces only the questionnaire
|
||||
// owned by userID. A missing row is the version-0 empty questionnaire.
|
||||
type CandidateQuestionnaireRepository interface {
|
||||
Get(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error)
|
||||
|
||||
// Save atomically advances the expected version and replaces the answer
|
||||
// rows. A concurrent identical winner is returned as an idempotent success;
|
||||
// a different winner returns ErrCandidateQuestionnaireVersionConflict.
|
||||
Save(ctx context.Context, expectedVersion int64, questionnaire domain.CandidateQuestionnaire) (domain.CandidateQuestionnaire, error)
|
||||
|
||||
// AdvanceOnboarding advances only candidate_questionnaire to
|
||||
// candidate_assessment; later onboarding steps are left unchanged.
|
||||
AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error
|
||||
}
|
||||
@@ -51,9 +51,11 @@ type UnitOfWork interface {
|
||||
IdentityRepositories
|
||||
ConsentRepositories
|
||||
CandidateProfileRepositories
|
||||
CandidateQuestionnaireRepositories
|
||||
AccountDeletionRequests() AccountDeletionRequests
|
||||
ConsentRevocationEffects() ConsentRevocationEffects
|
||||
OrganizationRepositories
|
||||
CompanyQuotas() CompanyQuotaRepository
|
||||
AssessmentBankRepositories
|
||||
Policies() PolicyRepository
|
||||
Deliveries() DeliveryRepository
|
||||
|
||||
@@ -333,6 +333,10 @@ type OpenCategoryInput struct {
|
||||
// is not the one in force are refused.
|
||||
GradingPolicyID domain.PolicyVersionID
|
||||
OpenedBy domain.AssessmentOperator
|
||||
// CatalogMetadata is the explicit public mapping reviewed for this exact
|
||||
// published bank opening. An opening without it is not exposed in the
|
||||
// public specialization catalog.
|
||||
CatalogMetadata *domain.AssessmentCategoryCatalogMetadata
|
||||
}
|
||||
|
||||
// OpenCategory makes a category available. It reads the referenced policy
|
||||
@@ -370,6 +374,14 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("store opening: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
if input.CatalogMetadata != nil {
|
||||
if input.CatalogMetadata.IsZero() {
|
||||
return fmt.Errorf("bind public catalog metadata: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if err := repository.BindCategoryCatalog(ctx, opening, *input.CatalogMetadata); err != nil {
|
||||
return fmt.Errorf("bind public catalog metadata: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -378,6 +390,24 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// SpecializationAvailability returns only catalog mappings whose opening,
|
||||
// current policy, live coverage, and published-family manifest still match.
|
||||
func (bank *Bank) SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
var availability []domain.SpecializationAvailability
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
availability, err = unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read current bank availability: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Bank.SpecializationAvailability - read catalog: %w", err)
|
||||
}
|
||||
return availability, nil
|
||||
}
|
||||
|
||||
// readGradingPolicy reads the referenced policy version and requires it to
|
||||
// be the version of the product policy in force now.
|
||||
func readGradingPolicy(ctx context.Context, unit outbound.UnitOfWork, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
|
||||
@@ -104,6 +104,16 @@ func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCa
|
||||
return domain.AssessmentCategoryOpening{}, bank.openErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) BindCategoryCatalog(context.Context, domain.AssessmentCategoryOpening, domain.AssessmentCategoryCatalogMetadata) error {
|
||||
bank.calls = append(bank.calls, "bind_catalog")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
bank.calls = append(bank.calls, "availability")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
if bank.opening == nil {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// Package companyquota resolves current organization limits and reserves
|
||||
// invitation or candidate-card usage in the caller's transaction.
|
||||
package companyquota
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrQuotaRepositoriesMissing = errors.New("company quota repositories are missing")
|
||||
ErrQuotaServiceUnavailable = errors.New("company quota service is unavailable")
|
||||
)
|
||||
|
||||
// Repositories is the transaction-scoped surface needed for one quota
|
||||
// operation. The service does not retain it, because the repositories are
|
||||
// bound to the caller's transaction.
|
||||
type Repositories interface {
|
||||
Policies() outbound.PolicyRepository
|
||||
CompanyQuotas() outbound.CompanyQuotaRepository
|
||||
}
|
||||
|
||||
// Service reads the current policy and delegates the atomic reservation. It
|
||||
// stores only the application clock and is safe to reuse between calls.
|
||||
type Service struct {
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService takes the application clock used once per operation. A nil
|
||||
// clock is a wiring error and panics at construction.
|
||||
func NewService(clock func() time.Time) *Service {
|
||||
if clock == nil {
|
||||
panic("companyquota.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{clock: clock}
|
||||
}
|
||||
|
||||
// ReserveInvitation atomically records a new invitation against the policy
|
||||
// effective at the operation's clock snapshot. Repeating invitationID is
|
||||
// idempotent even when the caller uses a different request key.
|
||||
func (service *Service) ReserveInvitation(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
invitationID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "Service.ReserveInvitation"
|
||||
if invitationID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
quota, repository, err := service.resolve(ctx, repositories, organization, location)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
decision, err := repository.ReserveInvitation(ctx, quota, invitationID)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve invitation usage: %w", location, err)
|
||||
}
|
||||
if !decision.RetryAt.IsZero() {
|
||||
decision.RetryAt = decision.RetryAt.UTC()
|
||||
}
|
||||
if err := validateDecision(quota, decision); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// ReserveCardView atomically counts a distinct candidate in the organization's
|
||||
// rolling view window. A repeat within the window refreshes the stored time
|
||||
// without charging another distinct view.
|
||||
func (service *Service) ReserveCardView(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "Service.ReserveCardView"
|
||||
if candidateID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
quota, repository, err := service.resolve(ctx, repositories, organization, location)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
decision, err := repository.ReserveCardView(ctx, quota, candidateID)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve card-view usage: %w", location, err)
|
||||
}
|
||||
if !decision.RetryAt.IsZero() {
|
||||
decision.RetryAt = decision.RetryAt.UTC()
|
||||
}
|
||||
if err := validateDecision(quota, decision); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
func (service *Service) resolve(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
location string,
|
||||
) (domain.CompanyQuota, outbound.CompanyQuotaRepository, error) {
|
||||
if service == nil || service.clock == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - service clock is missing: %w", location, ErrQuotaServiceUnavailable)
|
||||
}
|
||||
if repositories == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repositories are missing: %w", location, ErrQuotaRepositoriesMissing)
|
||||
}
|
||||
policies := repositories.Policies()
|
||||
quotaRepository := repositories.CompanyQuotas()
|
||||
if policies == nil || quotaRepository == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repository is missing: %w", location, ErrQuotaRepositoriesMissing)
|
||||
}
|
||||
now := service.clock().UTC()
|
||||
if now.IsZero() || now.Unix() < 0 {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - application clock must be set and non-negative: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, now)
|
||||
if err != nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - read effective product policy: %w", location, err)
|
||||
}
|
||||
quota, err := domain.NewCompanyQuota(organization, version, now)
|
||||
if err != nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - resolve organization quota: %w", location, err)
|
||||
}
|
||||
return quota, quotaRepository, nil
|
||||
}
|
||||
|
||||
func validateDecision(quota domain.CompanyQuota, decision outbound.CompanyQuotaDecision) error {
|
||||
switch {
|
||||
case decision.Allowed && !decision.RetryAt.IsZero():
|
||||
return errors.New("an allowed reservation cannot have a retry time")
|
||||
case decision.Reused && !decision.Allowed:
|
||||
return errors.New("a reused reservation must be allowed")
|
||||
case !decision.Allowed && (decision.Reused || decision.RetryAt.IsZero() || !decision.RetryAt.After(quota.At())):
|
||||
return errors.New("a denied reservation must be new and have a future retry time")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package companyquota
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type quotaTestPolicies struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
version domain.PolicyVersion
|
||||
err error
|
||||
calls int
|
||||
key domain.PolicyKey
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (policies *quotaTestPolicies) GetEffective(_ context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) {
|
||||
policies.calls++
|
||||
policies.key = key
|
||||
policies.at = at
|
||||
return policies.version, policies.err
|
||||
}
|
||||
|
||||
type quotaTestRepository struct {
|
||||
decision outbound.CompanyQuotaDecision
|
||||
err error
|
||||
invitationCalls int
|
||||
cardViewCalls int
|
||||
invitationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
invitationQuota domain.CompanyQuota
|
||||
cardViewQuota domain.CompanyQuota
|
||||
}
|
||||
|
||||
func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
repository.invitationCalls++
|
||||
repository.invitationQuota = quota
|
||||
repository.invitationID = invitationID
|
||||
return repository.decision, repository.err
|
||||
}
|
||||
|
||||
func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
repository.cardViewCalls++
|
||||
repository.cardViewQuota = quota
|
||||
repository.candidateID = candidateID
|
||||
return repository.decision, repository.err
|
||||
}
|
||||
|
||||
type quotaTestRepositories struct {
|
||||
policies *quotaTestPolicies
|
||||
quotas *quotaTestRepository
|
||||
}
|
||||
|
||||
func (repositories *quotaTestRepositories) Policies() outbound.PolicyRepository {
|
||||
return repositories.policies
|
||||
}
|
||||
|
||||
func (repositories *quotaTestRepositories) CompanyQuotas() outbound.CompanyQuotaRepository {
|
||||
return repositories.quotas
|
||||
}
|
||||
|
||||
func TestReserveInvitationReadsOneEffectivePolicySnapshotAndDelegates(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
|
||||
policy := quotaTestPolicyVersion(t, at.UTC().Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
decision := outbound.CompanyQuotaDecision{Allowed: true}
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: decision},
|
||||
}
|
||||
clockCalls := 0
|
||||
service := NewService(func() time.Time {
|
||||
clockCalls++
|
||||
return at
|
||||
})
|
||||
invitationID := uuid.New()
|
||||
|
||||
got, err := service.ReserveInvitation(context.Background(), repositories, organization, invitationID)
|
||||
if err != nil {
|
||||
t.Fatalf("ReserveInvitation() error = %v", err)
|
||||
}
|
||||
if got != decision || clockCalls != 1 || repositories.policies.calls != 1 ||
|
||||
repositories.policies.key != domain.ProductPolicyKey || !repositories.policies.at.Equal(at.UTC()) ||
|
||||
repositories.policies.at.Location() != time.UTC {
|
||||
t.Fatalf("decision=%+v clockCalls=%d policyReads=%d key=%s at=%s", got, clockCalls, repositories.policies.calls, repositories.policies.key, repositories.policies.at)
|
||||
}
|
||||
if repositories.quotas.invitationCalls != 1 || repositories.quotas.cardViewCalls != 0 || repositories.quotas.invitationID != invitationID {
|
||||
t.Fatalf("quota calls: invitations=%d views=%d invitationID=%s", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls, repositories.quotas.invitationID)
|
||||
}
|
||||
quota := repositories.quotas.invitationQuota
|
||||
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() || quota.Tier() != domain.OrganizationTierE0 ||
|
||||
quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 || !quota.At().Equal(at.UTC()) {
|
||||
t.Fatalf("reservation snapshot = org %s policy %s tier %s limits %d/%d at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit(), quota.At())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReserveCardViewReturnsAtomicReuseOrDenialDecision(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain, at.Add(-24*time.Hour), at.Add(-time.Hour))
|
||||
candidateID := uuid.New()
|
||||
ownerZone := time.FixedZone("owner", 3*60*60)
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision outbound.CompanyQuotaDecision
|
||||
}{
|
||||
{name: "repeat is allowed without another charge", decision: outbound.CompanyQuotaDecision{Allowed: true, Reused: true}},
|
||||
{name: "denied includes the earliest expiry", decision: outbound.CompanyQuotaDecision{RetryAt: at.Add(time.Hour).In(ownerZone)}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: test.decision},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
got, err := service.ReserveCardView(context.Background(), repositories, organization, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ReserveCardView() error = %v", err)
|
||||
}
|
||||
if got.Allowed != test.decision.Allowed || got.Reused != test.decision.Reused ||
|
||||
!got.RetryAt.Equal(test.decision.RetryAt) || repositories.quotas.cardViewCalls != 1 || repositories.quotas.invitationCalls != 0 ||
|
||||
repositories.quotas.candidateID != candidateID {
|
||||
t.Fatalf("decision=%+v calls=%d/%d candidateID=%s", got, repositories.quotas.cardViewCalls, repositories.quotas.invitationCalls, repositories.quotas.candidateID)
|
||||
}
|
||||
if !got.RetryAt.IsZero() && got.RetryAt.Location() != time.UTC {
|
||||
t.Fatalf("RetryAt() location = %s, want UTC", got.RetryAt.Location())
|
||||
}
|
||||
quota := repositories.quotas.cardViewQuota
|
||||
if quota.Tier() != domain.OrganizationTierE1 || quota.CardViewLimit() != 150 || quota.InvitationLimit() != 40 {
|
||||
t.Fatalf("E1 quota = tier %s limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceFailsClosedBeforeReservation(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
policyFailure := errors.New("policy store unavailable")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
organization domain.Organization
|
||||
policyError error
|
||||
clock time.Time
|
||||
want error
|
||||
}{
|
||||
{name: "policy unavailable", organization: organization, policyError: policyFailure, clock: at, want: policyFailure},
|
||||
{name: "clock is zero", organization: organization, clock: time.Time{}, want: domain.ErrInvalidCompanyQuota},
|
||||
{name: "clock predates organization trust", organization: organization, clock: at.Add(-48 * time.Hour), want: domain.ErrInvalidCompanyQuota},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy, err: test.policyError},
|
||||
quotas: "aTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
|
||||
}
|
||||
service := NewService(func() time.Time { return test.clock })
|
||||
_, err := service.ReserveInvitation(context.Background(), repositories, test.organization, uuid.New())
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("ReserveInvitation() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("quota repository was called: invitation=%d view=%d", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceDeniesE3AndInactiveE2WithoutFallback(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
level domain.OrganizationVerificationLevel
|
||||
basis domain.OrganizationVerificationBasis
|
||||
}{
|
||||
{name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview},
|
||||
{name: "E2 inactive in policy", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
organization := quotaTestOrganization(t, test.level, test.basis, at.Add(-24*time.Hour), at.Add(-time.Hour))
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
_, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.New())
|
||||
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("ReserveCardView() error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
if repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("quota repository calls = %d, want 0", repositories.quotas.cardViewCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceRejectsInconsistentRepositoryDecisions(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
|
||||
for _, decision := range []outbound.CompanyQuotaDecision{
|
||||
{Allowed: true, RetryAt: at.Add(time.Hour)},
|
||||
{Reused: true},
|
||||
{RetryAt: at},
|
||||
} {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: decision},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.New()); err == nil {
|
||||
t.Fatalf("ReserveInvitation(decision=%+v) succeeded, want invalid result", decision)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceRejectsMissingIDsBeforeReadingPolicy(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
repositories := "aTestRepositories{policies: "aTestPolicies{version: policy}, quotas: "aTestRepository{}}
|
||||
service := NewService(func() time.Time { return at })
|
||||
|
||||
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
|
||||
t.Fatalf("ReserveInvitation(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
|
||||
}
|
||||
if _, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
|
||||
t.Fatalf("ReserveCardView(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
|
||||
}
|
||||
if repositories.policies.calls != 0 || repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("repositories called for invalid IDs: policies=%d invitation=%d view=%d", repositories.policies.calls, repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func quotaTestOrganization(
|
||||
t *testing.T,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
basis domain.OrganizationVerificationBasis,
|
||||
createdAt, changedAt time.Time,
|
||||
) domain.Organization {
|
||||
t.Helper()
|
||||
updatedAt := createdAt
|
||||
if changedAt.After(updatedAt) {
|
||||
updatedAt = changedAt
|
||||
}
|
||||
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: uuid.New(), Name: "Example Company", VerificationLevel: string(level), VerificationBasis: string(basis),
|
||||
VerificationChangedAt: changedAt, Version: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreOrganization() error = %v", err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
func quotaTestPolicyVersion(t *testing.T, effectiveAt time.Time) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
policy := domain.DemoProductPolicyV1()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(1)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash := numbered.DocumentHash()
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
|
||||
Author: string(numbered.Author()), EffectiveAt: effectiveAt, CreatedAt: effectiveAt,
|
||||
Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Package questionnaire reads and version-saves a candidate's private questionnaire.
|
||||
package questionnaire
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("candidate questionnaire operation forbidden")
|
||||
ErrEmailNotVerified = errors.New("candidate questionnaire requires a confirmed email")
|
||||
)
|
||||
|
||||
// Service keeps questionnaire answers and onboarding movement in one
|
||||
// transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
|
||||
if transactor == nil {
|
||||
panic("questionnaire.NewService - transactor must not be nil")
|
||||
}
|
||||
if clock == nil {
|
||||
panic("questionnaire.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{transactor: transactor, clock: clock}
|
||||
}
|
||||
|
||||
// GetMyQuestionnaire reads only the questionnaire owned by the verified
|
||||
// candidate userID. Version zero means no questionnaire has been saved.
|
||||
func (service *Service) GetMyQuestionnaire(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "Service.GetMyQuestionnaire"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
var result domain.CandidateQuestionnaire
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
result, err = unit.CandidateQuestionnaires().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read questionnaire: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveMyQuestionnaire replaces the complete questionnaire at expectedVersion.
|
||||
// A changed stale save fails; an identical retry is a no-op. The first valid
|
||||
// save advances onboarding only from candidate_questionnaire.
|
||||
func (service *Service) SaveMyQuestionnaire(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
input domain.CandidateQuestionnaireInput,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "Service.SaveMyQuestionnaire"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
at := service.clock().UTC()
|
||||
if at.IsZero() {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
var result domain.CandidateQuestionnaire
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
repository := unit.CandidateQuestionnaires()
|
||||
current, err := repository.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read questionnaire: %w", location, err)
|
||||
}
|
||||
availability, err := unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read current task language availability: %w", location, err)
|
||||
}
|
||||
updated, changed, err := current.Replace(input, expectedVersion, at, availability)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - apply replacement: %w", location, err)
|
||||
}
|
||||
if changed {
|
||||
updated, err = repository.Save(ctx, expectedVersion, updated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - save replacement: %w", location, err)
|
||||
}
|
||||
}
|
||||
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - advance onboarding: %w", location, err)
|
||||
}
|
||||
result = updated
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrCandidateQuestionnaireVersionConflict) || errors.Is(err, domain.ErrCandidateQuestionnaireVersionConflict) {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateQuestionnaireVersionConflict)
|
||||
}
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
|
||||
user, err := unit.Users().GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return ErrEmailNotVerified
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package questionnaire
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type questionnaireTestTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor questionnaireTestTransactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(context.Context, outbound.UnitOfWork) error,
|
||||
) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type questionnaireTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
questionnaire outbound.CandidateQuestionnaireRepository
|
||||
bank outbound.AssessmentBankRepository
|
||||
}
|
||||
|
||||
func (unit questionnaireTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
|
||||
func (unit questionnaireTestUnit) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
|
||||
return unit.questionnaire
|
||||
}
|
||||
|
||||
func (unit questionnaireTestUnit) AssessmentBank() outbound.AssessmentBankRepository {
|
||||
return unit.bank
|
||||
}
|
||||
|
||||
type questionnaireTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
user domain.User
|
||||
err error
|
||||
getCalls int
|
||||
}
|
||||
|
||||
func (users *questionnaireTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
|
||||
users.getCalls++
|
||||
if users.err != nil {
|
||||
return domain.User{}, users.err
|
||||
}
|
||||
if users.user.ID != userID {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return users.user, nil
|
||||
}
|
||||
|
||||
type questionnaireTestRepository struct {
|
||||
questionnaire domain.CandidateQuestionnaire
|
||||
getCalls int
|
||||
saveCalls int
|
||||
advanceCalls int
|
||||
saveErr error
|
||||
advanceErr error
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) Get(_ context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
|
||||
repository.getCalls++
|
||||
if repository.questionnaire.IsZero() {
|
||||
return domain.EmptyCandidateQuestionnaire(userID)
|
||||
}
|
||||
return repository.questionnaire, nil
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) Save(
|
||||
_ context.Context,
|
||||
expectedVersion int64,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
repository.saveCalls++
|
||||
if repository.saveErr != nil {
|
||||
return domain.CandidateQuestionnaire{}, repository.saveErr
|
||||
}
|
||||
repository.questionnaire, _ = domain.RestoreCandidateQuestionnaire(domain.StoredCandidateQuestionnaire{
|
||||
UserID: questionnaire.UserID(), Version: expectedVersion + 1,
|
||||
Specializations: questionnaire.Specializations(), WorkFormats: questionnaire.WorkFormats(),
|
||||
CreatedAt: questionnaire.CreatedAt(), UpdatedAt: questionnaire.UpdatedAt(),
|
||||
})
|
||||
return repository.questionnaire, nil
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) AdvanceOnboarding(context.Context, uuid.UUID, time.Time) error {
|
||||
repository.advanceCalls++
|
||||
return repository.advanceErr
|
||||
}
|
||||
|
||||
type questionnaireTestBank struct {
|
||||
outbound.AssessmentBankRepository
|
||||
|
||||
availability []domain.SpecializationAvailability
|
||||
err error
|
||||
}
|
||||
|
||||
func (bank questionnaireTestBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
return bank.availability, bank.err
|
||||
}
|
||||
|
||||
func TestServiceRequiresVerifiedCandidateBeforeQuestionnaireAccess(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
scenario domain.Scenario
|
||||
verified bool
|
||||
wantErr error
|
||||
}{
|
||||
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
|
||||
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
|
||||
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
|
||||
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: test.scenario}
|
||||
if test.verified {
|
||||
user.EmailVerifiedAt = &now
|
||||
}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
|
||||
_, readErr := service.GetMyQuestionnaire(context.Background(), id)
|
||||
if !errors.Is(readErr, test.wantErr) {
|
||||
t.Fatalf("GetMyQuestionnaire() error = %v, want %v", readErr, test.wantErr)
|
||||
}
|
||||
_, saveErr := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
|
||||
if !errors.Is(saveErr, test.wantErr) {
|
||||
t.Fatalf("SaveMyQuestionnaire() error = %v, want %v", saveErr, test.wantErr)
|
||||
}
|
||||
wantReads, wantSaves, wantAdvances := 0, 0, 0
|
||||
if test.wantErr == nil {
|
||||
wantReads, wantSaves, wantAdvances = 2, 1, 1
|
||||
}
|
||||
if questionnaires.getCalls != wantReads || questionnaires.saveCalls != wantSaves || questionnaires.advanceCalls != wantAdvances {
|
||||
t.Fatalf("questionnaire calls = get %d, save %d, advance %d; want %d, %d, %d", questionnaires.getCalls, questionnaires.saveCalls, questionnaires.advanceCalls, wantReads, wantSaves, wantAdvances)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyQuestionnairePersistsChangesAndAdvancesAfterNoOp(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
Grades: []domain.GradeCode{domain.GradeJunior},
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
input := validQuestionnaireInput()
|
||||
|
||||
first, err := service.SaveMyQuestionnaire(context.Background(), id, 0, input)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(first) error = %v", err)
|
||||
}
|
||||
if first.Version() != 1 || questionnaires.saveCalls != 1 || questionnaires.advanceCalls != 1 {
|
||||
t.Fatalf("first save version/calls = %d/%d/%d; want 1/1/1", first.Version(), questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
input.Specializations[0].SelfAssessedGrade = domain.GradeSenior
|
||||
second, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(self-assessed senior) error = %v", err)
|
||||
}
|
||||
if second.Version() != 2 || second.Specializations()[0].SelfAssessedGrade != domain.GradeSenior {
|
||||
t.Fatalf("saved self-assessment = version %d grade %q; want version 2 senior", second.Version(), second.Specializations()[0].SelfAssessedGrade)
|
||||
}
|
||||
if _, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input); err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(stale identical retry) error = %v", err)
|
||||
}
|
||||
if questionnaires.saveCalls != 2 || questionnaires.advanceCalls != 3 {
|
||||
t.Fatalf("save/onboarding calls = %d/%d; want 2/3", questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyQuestionnaireRejectsUnavailableLanguageBeforeMutation(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguagePython},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
|
||||
_, err := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
|
||||
fieldError, ok := errors.AsType[*domain.CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" {
|
||||
t.Fatalf("SaveMyQuestionnaire(unavailable language) error = %v; want task-language field error", err)
|
||||
}
|
||||
if questionnaires.saveCalls != 0 || questionnaires.advanceCalls != 0 {
|
||||
t.Fatalf("mutation calls after invalid language = save %d advance %d; want 0/0", questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func validQuestionnaireInput() domain.CandidateQuestionnaireInput {
|
||||
return domain.CandidateQuestionnaireInput{
|
||||
Specializations: []domain.QuestionnaireSpecialization{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
SelfAssessedGrade: domain.GradeJunior,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}},
|
||||
WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user