feat(visibility): add the candidate publication, hiding and search status contract
This commit is contained in:
1 parent
4436f626a3
commit
0529601021
87 files changed
+21456
-83
No files matched your search
+39
-1
@@ -702,7 +702,7 @@ Decisions:
|
||||
- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented.
|
||||
- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration.
|
||||
- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)).
|
||||
- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are evidence of the publication history of TASK-088, which must keep them with their times. Adding a field scope to C2 rows later is an additive migration and contract change.
|
||||
- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the history of TASK-088 (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change.
|
||||
- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`.
|
||||
- Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent.
|
||||
- Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output.
|
||||
@@ -802,6 +802,44 @@ Decisions:
|
||||
- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit.
|
||||
- Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does.
|
||||
|
||||
### Candidate visibility
|
||||
|
||||
Implemented as storage, domain, and the source contract (TASK-088): the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test.
|
||||
|
||||
Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced:
|
||||
|
||||
- `candidate_publications`: one row per candidate, created by the first explicit publication, so a new profile has no row and is closed. Columns: `state` (`published` or `closed`), `fields` (a canonical array of card field codes, empty exactly when closed), `consent_record_id`, `published_at`, `closed_at`, `version`, and times. The card field codes are a closed set (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); the full name, a contact, and the lowest salary have no code, and the function `candidate_card_fields_are_canonical` with a CHECK refuses anything else, so no row can publish them.
|
||||
- `candidate_search_statuses`: one row per candidate who ever set the status. `status` is `looking` or `not_looking`; `looking` stores `confirmed_at`, `lapses_at`, and `policy_version_id`, and `not_looking` stores none of them (a CHECK ties the three together). The only foreign key is `users`, and a trigger checks `policy_version_id` against `policy_versions` (SQLSTATE 23503, constraint name `candidate_search_statuses_policy_fkey`), because a real foreign key would make PostgreSQL refuse TRUNCATE of the immutable policy table before its own trigger could answer: the table has no consent column and no reference to the ledger, and a test reads the catalog to prove it.
|
||||
- `candidate_hidden_organizations`: the primary key `(user_id, organization_id)` makes a hiding unique per candidate and organization; `organization_id` references `organizations` with `ON DELETE RESTRICT`. A BEFORE INSERT trigger (`candidate_hidden_organizations_enforce_limit`) bounds one candidate to 1000 records, serializing the inserts of one candidate through a no-key-update lock on the account row, and fails with SQLSTATE 23514 and the constraint name `candidate_hidden_organizations_limit`. The index on `(organization_id, user_id)` serves the organization side, which has to exclude hidden candidates without learning who hid it.
|
||||
- `candidate_privacy_events`: the append-only history (a trigger refuses every UPDATE with `candidate_privacy_events_immutable`, and refuses DELETE only while the account is verified, with `candidate_privacy_events_retained`; TRUNCATE stays allowed for test isolation). It holds the kind, the time, the published field set and the C2 record of a publication event, and only the organization identifier for a hiding event (the candidate's read joins the current name, so the table holds no text about an organization); a CHECK fixes the shape of every kind. It never holds a profile value or a name. A trigger refuses DELETE while the account is confirmed (`candidate_privacy_events_retained`, the same condition as `consent_records_refuse_delete`, to be extended by the retention rule and the account deletion procedure), a trigger on `users` refuses deleting a confirmed account that has history with the same constraint name (the cascade runs after the account row is gone, so the row trigger alone cannot see it), and the account reference cascades, so the unverified account cleanup removes the rows of an account it deletes. The hide and unhide records are sensitive: they say which employer a candidate avoids.
|
||||
|
||||
Decisions:
|
||||
|
||||
- A profile is closed by default. Nothing in the account, the profile, the questionnaire, or an assessment creates a row, and the integration test saves a profile and checks that all four tables stay empty. The domain reads a missing row as version 0, closed with the reason `never_published`, not looking, and hiding nobody.
|
||||
- C2 stays in the consent ledger; the publication references it. Duplicating the consent state would let two tables disagree about whether a candidate agreed. `candidate_publications` therefore holds only what the ledger deliberately does not carry (which fields and when) and a reference to the C2 record behind them. The composite foreign key `(consent_record_id, user_id, consent_purpose)` over the unique index `consent_records_id_subject_purpose_key` (added by this migration; the record id is already unique, so it restricts nothing) accepts only a C2 record of the same account, and a record that a publication refers to cannot be deleted. The effective state is computed: `ReadCandidatePublication` joins the revocation stamp of the record in one statement, and the card is `published` only while the stored state is `published` and the record is unrevoked. A revocation of C2 closes the card at once without any write here, and a later C2 grant opens nothing: the publication stays bound to the revoked record, so the candidate publishes again explicitly and the new publication binds to the new record. The body of the publish operation carries no consent identifier; the usecase binds the account's current unrevoked C2 record in the same transaction as the write, and it MUST take it with the port method that issues `LockCurrentC2Record` (`SELECT ... FOR SHARE`), not with `ConsentLedger().Current`, otherwise the race with a revocation returns, and without one answers 409 `state_conflict`.
|
||||
- The search status is not a consent. It has its own table, its own version, and no reference to the ledger, and `domain.SearchStatus` knows neither the publication nor the hidden organizations, so applying a status cannot change them. The integration test sets, confirms, and clears the status in a fixture and compares the raw rows of the consent ledger, the publication, and the hidden organizations before and after: they are equal.
|
||||
- The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task.
|
||||
- Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale.
|
||||
- Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains.
|
||||
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). That belongs to the usecases that do not exist yet; this task stores the settings and defines the contract. The search status never closes a grant.
|
||||
- History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger).
|
||||
- Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do.
|
||||
|
||||
- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read: TASK-185, TASK-089, TASK-090) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table.
|
||||
- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path (TASK-064) must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants.
|
||||
- Publish and revoke race. The publish transaction takes the current C2 with `LockCurrentC2Record` (`SELECT ... FOR SHARE`) and writes the publication under that lock, then re-reads the effective state with `ReadCandidatePublication` in the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders.
|
||||
- Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (`DeleteUnverifiedUsersRegisteredBefore`) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade.
|
||||
- Two kinds of 409 `state_conflict` are told apart by `errors[]`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 and `candidate_hidden_organizations_limit`, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success.
|
||||
- A new card field is a contract change and a migration. The codes are listed in the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables, as well as in the `CardField` enum, `domain.CardField`, and the card builder.
|
||||
|
||||
Content of the card (hard requirements for TASK-089, which builds it):
|
||||
|
||||
- Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
||||
- A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published. `domain.CardTextLooksLikeContact` is the check the builder must apply to every free text; it errs on the side of dropping.
|
||||
- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion of TASK-089, not decided here (see the open question in the API README).
|
||||
|
||||
The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result (TASK-185) must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks.
|
||||
|
||||
## Frontend
|
||||
|
||||
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
|
||||
|
||||
@@ -370,6 +370,22 @@ Unit tests (`make -C backend test`) check the profile rules without a database:
|
||||
|
||||
`TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays.
|
||||
|
||||
## Candidate visibility tests
|
||||
|
||||
Unit tests (`make -C backend test`) check the visibility rules without a database:
|
||||
|
||||
- `internal/domain/visibility_test.go`: the card field set is canonical, closed, and refuses the full name, any contact, and the salary; a publication request needs a field to publish and none to close; a new profile is closed and never published; publishing needs an active C2 and names no consent; the order of checks (a future version, an unchanged state over a stale version, a stale change, a missing consent); a revoked C2 closes the card and a new C2 does not reopen it; the search status lapses after the interval of the policy to the non-public status without a write, is confirmed again explicitly, and takes the interval from the policy version; stored rows that break an invariant are rejected; the types log only identifiers.
|
||||
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: by the contract bundle, the operations follow the conventions (the CSRF scheme exactly for changes, the version in the body, no Idempotency-Key or If-Match, the same 404 for hiding, 204 without a 404 for lifting); the publication and the search status carry no consent and reach no schema of each other; **the anonymous card and the preview reach no profile, contact, consent, invitation, or organization schema and have no property that names or identifies a person**, and no organization path reaches a setting; through the generated server the schema rejects a contact as a card field, a consent identifier, and a client-sent time before the implementation, a valid request answers 501, and a denied session answers 401.
|
||||
- `frontend/src/shared/api/privacy-contract.test.ts`: the generated Zod schemas read a new candidate as closed and not looking at version 0, reject a card field that is a name, a contact, or the salary, strip a consent, a time, and an interval from the parsed requests, keep the card closed to contacts, and the generated organization, invitation, need, profile, and consent files hold no setting keys.
|
||||
|
||||
`TestCandidatePrivacyStorage` in `backend/integration_test/candidate_privacy_test.go` uses `bootstrap(t, postgresService)`; `candidatePrivacyTables` belong to `usersDependentTables`:
|
||||
|
||||
- A new profile has no published state: after saving a profile all four tables are empty and the reads return no row. A hidden organization is unique per candidate and belongs to the candidate; an unknown organization is refused by the reference; lifting deletes once; the 1001st record is refused by the trigger.
|
||||
- Publication: the foreign key accepts only a C2 record of the same account; a revocation in the ledger closes the card without a write; a new C2 grant publishes nothing; a stale update returns no row; the constraints refuse a contact as a field, a wrong order, and a wrong state shape.
|
||||
- Search status: in a fixture the status is set, confirmed, and cleared, and the raw rows of the consent ledger, the publication, and the hidden organizations stay equal; looking stores the confirmation under the policy version with the interval of the policy; a lapse changes no row; the constraints refuse looking without its confirmation; the table has no consent column and references only users.
|
||||
- Closing over a revoked C2 normalizes the stored row and records the closing; an organization reads a publication only through the effective view and not when it hides the reading organization (the same no-row answer as for an unpublished profile); a revocation racing with a publication, held under `LockCurrentC2Record`, waits for it and closes the card after it, or finds nothing to lock; eight concurrent hidings at 999 records let exactly one through; the unverified account cleanup removes the hiding records and history of an unverified account and spares a confirmed one. `backend/db/privacy_queries_test.go` fails when a query other than the three settings queries names `candidate_publications`, and `TestCardTextLooksLikeContact` pins the drop of free text that looks like a contact.
|
||||
- History: append-only (UPDATE refused, DELETE refused while the account is confirmed), identifiers only, the shape of each kind is checked, pages continue by position, and the published fields and the C2 record are kept with their time. No privacy table has a column for a profile value, a name, a contact, or a file.
|
||||
|
||||
## Assessment bank tests
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
|
||||
|
||||
+39
-1
@@ -702,7 +702,7 @@ contact_grant относится к паре кандидат-компания
|
||||
- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы.
|
||||
- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией.
|
||||
- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)).
|
||||
- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения - доказательства истории публикации из TASK-088, которая обязана хранить их со временем. Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта.
|
||||
- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории TASK-088 (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта.
|
||||
- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`.
|
||||
- Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие.
|
||||
- Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля.
|
||||
@@ -802,6 +802,44 @@ contact_grant относится к паре кандидат-компания
|
||||
- Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии.
|
||||
- Приватность. Значения - ПДн кандидата: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent` и `CandidateProfile` скрывают себя в выводе `fmt` и `slog`, `CandidateProfile` логирует только идентификатор аккаунта и версию, ошибки домена называют поле и правило, но не значение, а метки метрик никогда не берутся из профиля. Ни один запрос не выбирает профиль чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер никогда не логирует и не оборачивает `pgconn.PgError.Detail` (там строка с именами и телефонами) и сообщает только SQLSTATE и имя ограничения, как адаптер организаций.
|
||||
|
||||
### Видимость кандидата
|
||||
|
||||
Реализовано как хранилище, домен и исходный контракт (TASK-088): миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом.
|
||||
|
||||
Четыре независимых состояния, у каждого своя таблица и своя версия. Ни один оператор одной таблицы не пишет другую, а согласие C2 не копируется и не заменяется:
|
||||
|
||||
- `candidate_publications`: одна строка на кандидата, создается первой явной публикацией, поэтому у нового профиля строки нет и он закрыт. Столбцы: `state` (`published` или `closed`), `fields` (канонический массив кодов полей карточки, пустой ровно при `closed`), `consent_record_id`, `published_at`, `closed_at`, `version` и времена. Коды полей карточки - закрытый набор (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); у полного имени, контакта и минимальной зарплаты кода нет, а функция `candidate_card_fields_are_canonical` с CHECK отклоняет все остальное, поэтому ни одна строка не может их опубликовать.
|
||||
- `candidate_search_statuses`: одна строка на кандидата, который хоть раз задавал статус. `status` - `looking` или `not_looking`; `looking` хранит `confirmed_at`, `lapses_at` и `policy_version_id`, а `not_looking` не хранит ничего из этого (CHECK связывает три значения). Внешний ключ только на `users`, а `policy_version_id` проверяет триггер по `policy_versions` (SQLSTATE 23503, имя ограничения `candidate_search_statuses_policy_fkey`), потому что настоящий внешний ключ заставил бы PostgreSQL отказать в TRUNCATE неизменяемой таблицы политик раньше ее собственного триггера: у таблицы нет столбца согласия и ссылки на журнал, тест читает каталог и это доказывает.
|
||||
- `candidate_hidden_organizations`: первичный ключ `(user_id, organization_id)` делает скрытие уникальным для пары кандидат-организация; `organization_id` ссылается на `organizations` с `ON DELETE RESTRICT`. Триггер BEFORE INSERT (`candidate_hidden_organizations_enforce_limit`) ограничивает кандидата 1000 записями, сериализуя вставки одного кандидата блокировкой no-key-update строки аккаунта, и падает с SQLSTATE 23514 и именем ограничения `candidate_hidden_organizations_limit`. Индекс по `(organization_id, user_id)` обслуживает сторону организации, которая должна исключать скрывших кандидатов, не узнавая, кто ее скрыл.
|
||||
- `candidate_privacy_events`: журнал только для добавления (триггер запрещает любой UPDATE с `candidate_privacy_events_immutable` и запрещает DELETE, только пока аккаунт подтвержден, с `candidate_privacy_events_retained`; TRUNCATE для изоляции тестов разрешен). В нем вид события, время, набор опубликованных полей и запись C2 для события публикации, а для скрытия - только идентификатор организации (чтение кандидата присоединяет текущее название, поэтому в таблице нет текста об организации); CHECK задает форму каждого вида. Значений профиля и имен там нет. Триггер запрещает DELETE, пока аккаунт подтвержден (`candidate_privacy_events_retained`, то же условие, что у `consent_records_refuse_delete`; его расширят правило хранения и процедура удаления аккаунта), триггер на `users` запрещает удалять подтвержденный аккаунт с историей под тем же именем ограничения (каскад выполняется, когда строки аккаунта уже нет, и строковый триггер один этого не видит), а ссылка на аккаунт каскадная, поэтому очистка неподтвержденных аккаунтов удаляет строки удаляемого аккаунта. Записи о скрытии и снятии скрытия чувствительны: они говорят, каких работодателей кандидат избегает.
|
||||
|
||||
Решения:
|
||||
|
||||
- Профиль закрыт по умолчанию. Ничто в аккаунте, профиле, анкете или оценке не создает строку, а интеграционный тест сохраняет профиль и проверяет, что все четыре таблицы остаются пустыми. Домен читает отсутствие строки как версию 0, закрытый профиль с причиной `never_published`, статус "не ищет" и отсутствие скрытых организаций.
|
||||
- C2 остается в журнале согласий, публикация на него ссылается. Дублирование состояния согласия позволило бы двум таблицам расходиться в том, согласился ли кандидат. Поэтому `candidate_publications` хранит только то, чего журнал намеренно не несет (какие поля и когда), и ссылку на запись C2, на которой публикация держится. Составной внешний ключ `(consent_record_id, user_id, consent_purpose)` по уникальному индексу `consent_records_id_subject_purpose_key` (добавлен этой миграцией; идентификатор записи и так уникален, поэтому индекс ничего не ограничивает) принимает только запись C2 того же аккаунта, а запись, на которую ссылается публикация, удалить нельзя. Действующее состояние вычисляется: `ReadCandidatePublication` присоединяет отметку отзыва записи в одном операторе, и карточка `published` только пока сохраненное состояние `published`, а запись не отозвана. Отзыв C2 закрывает карточку сразу, без записи в эту таблицу, а новая выдача C2 ничего не открывает: публикация остается привязанной к отозванной записи, кандидат публикует заново явно, и новая публикация привязывается к новой записи. В теле операции публикации нет идентификатора согласия; юзкейс привязывает текущую неотозванную запись C2 аккаунта в той же транзакции, что и запись, и ОБЯЗАН брать ее методом порта, который выполняет `LockCurrentC2Record` (`SELECT ... FOR SHARE`), а не `ConsentLedger().Current`, иначе гонка с отзывом возвращается, а без нее отвечает 409 `state_conflict`.
|
||||
- Статус поиска - не согласие. У него своя таблица, своя версия и нет ссылки на журнал, а `domain.SearchStatus` не знает ни публикации, ни скрытых организаций, поэтому применение статуса не может их изменить. Интеграционный тест в фикстуре задает, подтверждает и снимает статус и сравнивает сырые строки журнала согласий, публикации и скрытых организаций до и после: они равны.
|
||||
- Истечение `looking` берется из версионированной политики и только сужает видимость. 30 дней - это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (демо-версия 1: 30), поэтому владелец меняет срок публикацией новой версии политики, а не константой или конфигурацией. Подтверждение фиксирует `lapses_at` и сохраняет `policy_version_id`, поэтому последующее изменение политики не сдвигает сохраненные времена, а каждая строка называет политику, по которой создана, как требует раздел политик. Само истечение вычисляется (`SearchStatus.Effective(now)` дает `looking`, только пока `now` раньше `lapses_at`) и нигде не записывается: ни процесс, ни задача, ни расхождение часов не превратит истекший статус во что-то более публичное, сохраненная строка хранит слова кандидата, а ответ показывает `value` `not_looking` и `lapsed` true. Кандидат подтверждает снова значением `looking`, которое заменяет `confirmed_at`. Напоминание до истечения - запланированное уведомление, не часть этой задачи.
|
||||
- Версии. У каждой настройки своя `version` (0 - отсутствие строки), она проверяется в самом операторе, как у профиля: `UpdateCandidatePublication` и `UpdateCandidateSearchStatus` меняют строку только если сохраненная версия равна прочитанной вызывающим, а для устаревшей строка не возвращается (412 `version_conflict`). Порядок в домене совпадает с контрактом: версия выше текущей - конфликт, неизмененная действующая настройка - успех даже при устаревшей версии, любое другое изменение по устаревшей версии - конфликт, а публикации нужна действующая C2. Поскольку настройки независимы, изменение одной никогда не делает устаревшей другую.
|
||||
- Скрытые организации принадлежат кандидату и защищены от перебора. Запись принадлежит кандидату: ни один запрос стороны организации ее не выбирает, а организация не отличает скрывшего кандидата от неопубликованного. Скрытие по идентификатору не должно стать способом спросить, существует ли организация. Внешний ключ отклоняет неизвестную организацию (SQLSTATE 23503), а юзкейс обязан ответить на это так же, как на организацию, которую кандидат не видит: тот же 404 `not_found` с тем же телом, без другого времени ответа или кода. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован, открытый вопрос), поэтому скрытие не раскрывает того, что кандидат не мог прочитать раньше. Снятие скрытия - DELETE, который отвечает 204 на любой корректный идентификатор и потому ничего не раскрывает; событие истории пишется, только если строка была удалена. Идентификаторы - случайные UUIDv7, а оставшийся перебор покрывает общий лимит запросов.
|
||||
- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Это относится к юзкейсам, которых еще нет; эта задача хранит настройки и задает контракт. Статус поиска разрешение никогда не закрывает.
|
||||
- История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий).
|
||||
- Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные.
|
||||
|
||||
- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов: TASK-185, TASK-089, TASK-090) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу.
|
||||
- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 (TASK-064) сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает.
|
||||
- Гонка публикации и отзыва. Транзакция публикации берет текущую C2 через `LockCurrentC2Record` (`SELECT ... FOR SHARE`), пишет публикацию под этой блокировкой и затем перечитывает действующее состояние `ReadCandidatePublication` в той же транзакции, чтобы построить ответ. Отметка отзыва - UPDATE той же строки, поэтому он либо фиксируется раньше (блокировка не вернет строку, публикация отклонена с 409), либо ждет фиксации публикации и закрывает карточку сразу после; интеграционный тест удерживает блокировку и доказывает оба порядка.
|
||||
- Подтвержденный email. Публикация, скрытие и история существуют только у аккаунтов с подтвержденным email (требование юзкейса). Очистка неподтвержденных аккаунтов (`DeleteUnverifiedUsersRegisteredBefore`) удаляет их записи согласий явно и столкнулась бы с ограничивающей ссылкой публикации на запись C2, поэтому отсутствие публикации у неподтвержденного аккаунта - требование юзкейса, а не физическая невозможность: очистка работает и для неподтвержденного аккаунта, у которого есть C2, публикация и история, и для C2, отозванной и выданной снова (это проверяет интеграционный сценарий, и он зависит от порядка применения изменяющих операторов очистки). Записи скрытия и история удаляются каскадом.
|
||||
- Два вида 409 `state_conflict` различаются через `errors[]`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Предел скрытий обеспечивает триггер под блокировкой строки аккаунта; когда вставка падает с SQLSTATE 23514 и `candidate_hidden_organizations_limit`, адаптер обязан перечитать пару перед ответом 409, потому что параллельный PUT той же пары при 999 записях мог ее создать, а идемпотентный ответ - 200; интеграционный тест запускает восемь параллельных вставок при 999 записях и ожидает ровно один успех.
|
||||
- Новое поле карточки - это изменение контракта и миграция. Коды перечислены в функции `candidate_card_fields_are_canonical` и в CHECK таблиц публикации и событий, а также в enum `CardField`, `domain.CardField` и построителе карточки.
|
||||
|
||||
Содержимое карточки (жесткие требования к TASK-089, который ее строит):
|
||||
|
||||
- В карточку попадают только значения, которые кандидат подтвердил; неподтвержденное предложение (статус `extracted`) и неизвестное значение не попадают никогда, что бы ни говорил набор полей.
|
||||
- Свободный текст (тег стека, софт-скилл, место), похожий на контакт (адрес email, номер телефона, URL или домен, ссылка Telegram, @handle), отбрасывается и не публикуется. Проверка, которую построитель обязан применять к каждому свободному тексту, - `domain.CardTextLooksLikeContact`; она ошибается в сторону отбрасывания.
|
||||
- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки TASK-089, здесь не решаются (см. открытый вопрос в README API).
|
||||
|
||||
Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации (TASK-185) нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами.
|
||||
|
||||
## Frontend
|
||||
|
||||
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
|
||||
|
||||
@@ -370,6 +370,22 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
|
||||
|
||||
## Тесты видимости кандидата
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила видимости без базы:
|
||||
|
||||
- `internal/domain/visibility_test.go`: набор полей карточки канонический, закрытый и отклоняет полное имя, любой контакт и зарплату; запрос публикации требует поле для публикации и не допускает его при закрытии; новый профиль закрыт и не публиковался; публикации нужна действующая C2, а согласие она не называет; порядок проверок (будущая версия, неизмененное состояние при устаревшей версии, устаревшее изменение, нет согласия); отозванная C2 закрывает карточку, а новая ее не открывает; статус поиска истекает через срок политики до непубличного статуса без записи, подтверждается заново явно и берет срок из версии политики; сохраненные строки, нарушающие инвариант, отклоняются; типы пишут в журнал только идентификаторы.
|
||||
- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: по бандлу контракта операции следуют соглашениям (схема CSRF ровно для изменений, версия в теле, нет Idempotency-Key и If-Match, одинаковый 404 для скрытия, 204 без 404 для снятия); публикация и статус поиска не несут согласия и не достигают схем друг друга; **анонимная карточка и предпросмотр не достигают схем профиля, контакта, согласия, приглашения или организации и не имеют свойства, называющего или идентифицирующего человека**, а путь организации не достигает настроек; через сгенерированный сервер схема отклоняет контакт как поле карточки, идентификатор согласия и время от клиента до реализации, валидный запрос отвечает 501, а отказанная сессия - 401.
|
||||
- `frontend/src/shared/api/privacy-contract.test.ts`: сгенерированные схемы Zod читают нового кандидата как закрытого и не ищущего с версией 0, отклоняют поле карточки, которое является именем, контактом или зарплатой, убирают согласие, время и срок из разобранных запросов, не пускают контакты в карточку, а в сгенерированных файлах организации, приглашения, потребности, профиля и согласий нет ключей настроек.
|
||||
|
||||
`TestCandidatePrivacyStorage` в `backend/integration_test/candidate_privacy_test.go` использует `bootstrap(t, postgresService)`; `candidatePrivacyTables` входят в `usersDependentTables`:
|
||||
|
||||
- У нового профиля нет состояния публикации: после сохранения профиля все четыре таблицы пусты, а чтения не возвращают строки. Скрытая организация уникальна для кандидата и принадлежит ему; неизвестную организацию отклоняет ссылка; снятие удаляет один раз; 1001-ю запись отклоняет триггер.
|
||||
- Публикация: внешний ключ принимает только запись C2 того же аккаунта; отзыв в журнале закрывает карточку без записи; новая выдача C2 ничего не публикует; устаревшее обновление не возвращает строку; ограничения отклоняют контакт как поле, неверный порядок и неверную форму состояния.
|
||||
- Статус поиска: в фикстуре статус задается, подтверждается и снимается, а сырые строки журнала согласий, публикации и скрытых организаций остаются равными; `looking` хранит подтверждение под версией политики со сроком политики; истечение не меняет строк; ограничения отклоняют `looking` без подтверждения; в таблице нет столбца согласия, а внешний ключ ведет только на аккаунты.
|
||||
- Закрытие поверх отозванной C2 нормализует сохраненную строку и записывает закрытие; организация читает публикацию только через действующее представление и не читает, если скрыта (тот же ответ без строки, что и для неопубликованного профиля); отзыв, гоняющийся с публикацией, удерживаемой под `LockCurrentC2Record`, ждет ее и закрывает карточку после, либо не находит что блокировать; восемь параллельных скрытий при 999 записях пропускают ровно одно; очистка неподтвержденных аккаунтов удаляет записи скрытия и историю неподтвержденного аккаунта и не трогает подтвержденный. `backend/db/privacy_queries_test.go` падает, когда запрос, кроме трех запросов настроек, называет `candidate_publications`, а `TestCardTextLooksLikeContact` фиксирует отбрасывание свободного текста, похожего на контакт.
|
||||
- История: только добавление (UPDATE отклоняется, DELETE отклоняется, пока аккаунт подтвержден), только идентификаторы, форма каждого вида проверена, страницы продолжаются по позиции, опубликованные поля и запись C2 хранятся со временем. Ни в одной таблице видимости нет столбца для значения профиля, имени, контакта или файла.
|
||||
|
||||
## Тесты банка заданий
|
||||
|
||||
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. С in-memory подделками репозитория и единицы работы usecase-тесты доказывают: одновременный идентичный импорт сообщает версию как неизмененную, а одновременный импорт с другим содержимым отклоняется; sentinel-ошибки гонок базы становятся отказами с подходящей причиной; публикация после взятия блокировки категории выводит из обращения более старую опубликованную версию и отклоняется, если опубликована более новая; открытие требует действующую версию политики; доступность отклоняется, когда число опубликованных семейств падает ниже требования открытия или когда версия политики открытия больше не действует; более старый одобренный черновик отклоняется, пока существует более новая версия: черновик, опубликованная или выведенная из обращения. `internal/adapter/secondary/postgres/assessment_bank_test.go` проверяет, что ограничения банка преобразуются в свои sentinel-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции.
|
||||
|
||||
Reference in new issue
Block a user