feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

+66 -1
View File
@@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet.
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet.
### Errors
@@ -483,6 +483,71 @@ Open legal item: whether `c2` is a consent to the distribution of personal data
No new problem code is added: the contract reuses `validation_failed` and `unauthenticated`. `TestConsentSchemaValidationPrecedesImplementation`, `TestConsentAccessBeforeImplementation`, and `TestConsentDTOsCarryNoHashSubjectOrContact` pin the generated server, and `frontend/src/shared/api/consent-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of hash, subject, and contact fields.
### Organizations
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (TASK-077, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned in TASK-078 and TASK-079.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/organizations` | `ListMyOrganizations` | session | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
| `POST /api/v1/organizations` | `CreateOrganization` | session and CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | session | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` |
| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | session and CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 412 `version_conflict`, 429 |
Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer.
Active organization context (decision of TASK-077):
- The context is not stored on the server. Every organization-scoped operation, including the needs and invitations of this contract, names its organization in the path `org_id`, and the server checks that identifier against the active membership of the session account on every request. The identifier grants nothing; a switch between organizations is another `org_id` in the client's routes.
- Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (TASK-079 wants the next read closed, not the browser cache expired), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. TASK-085 clears the tenant-scoped client queries on a switch, which fits a client-side context.
- `ListMyOrganizations` is the directory of contexts: the organizations where the caller has an `active` membership, newest membership first, with the caller's role and state. A client picks the context from it, may remember the last choice in the browser as a convenience, and reads the list again after a 404 from an organization path. A person with several memberships sees all of them and works in one at a time; the rights and the data of the organizations stay separate.
Access:
- An employer account only. A candidate account answers 403 `forbidden` on all four operations, and an account without a session answers 401.
- `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned.
- `CreateOrganization` creates the organization and the owner membership of the caller in one transaction (role `owner`, state `active`), so an organization never exists without an owner; the database refuses to commit one that has none. The body has no owner, role, membership, or verification field.
Memberships:
- A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` of TASK-082); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own (TASK-082, TASK-084), and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change.
- The role lives in the membership only. `Organization`, `OrganizationCreate`, `OrganizationUpdate`, and `CandidateOrganizationCard` have no role, owner, or member field. The caller reads their own role in `OrganizationMembership` from `ListMyOrganizations`; the DTO names no account.
- There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it (TASK-081 and TASK-082). A person may hold independent memberships in several organizations.
- Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned in TASK-083 and TASK-463. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned in TASK-084 and TASK-085 and add operations, not fields, to this contract.
Profile:
- `OrganizationCreate` requires only `name`. The profile fields are `name` (1-200 characters, no surrounding whitespace or line break, because a consent record keeps a copy), `description` (1-2000 characters, nullable, line breaks allowed), `sphere` (1-100 characters, nullable, free text: the PRD has no sphere taxonomy, and a taxonomy code would be an additive field), `contacts`, and `representatives`.
- `contacts` is one object with `website`, `email`, `phone`, and `telegram`, all required and nullable, so it is the request field and the stored value alike. They are public company channels: an https website without credentials, a port, or an IP address, a careers mailbox, an E.164 phone number, and a Telegram username with the leading `@`. The contract holds no personal contact of an employee, and the server cannot tell a personal address from a company one, so the owner answers for the content; a complaint about an organization goes through a support case. The server never fetches the website.
- `representatives` is a list of up to ten `{name, job_title}` entries in the order the owner gave them. A representative is presentation only: not a member, with no account link, no contact, and no right, and a member does not become one by joining. The name is personal data of an employee that the owner publishes, which makes the open question below.
- `UpdateOrganization` uses explicit field replacement, as `UpdateOrganizationNeed` does: a present field replaces that field as a whole, an absent field stays unchanged, and `contacts` and `representatives` are never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. ogen generates `OptNil` values for the nullable fields and a plain slice for `representatives`, where nil is absent and `[]` is an empty replacement; a handler must test it with `!= nil`, never with `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`).
- Text is plain: clients show every field as text, never as HTML. Domain rules that need more than the schema, such as the host rules of the website, answer 400 with a pointer (`/contacts/website`, `/representatives/0/job_title`); the examples show the shapes.
Verification level:
- `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (TASK-086 adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own.
- No request sets or raises a level or its basis: `OrganizationCreate` and `OrganizationUpdate` are closed objects with only the profile fields, no operation of the contract changes the level, and editing the description, the contacts, or the representatives leaves it as it is. The database keeps the level and the basis in their own columns that the profile statement never writes, and a CHECK ties each level to its own bases. `OrganizationVerification` is read-only: `level`, `basis`, and `changed_at`; the scope of the check and the history of changes (PRD FR07) arrive as additive fields with the first process.
- The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. The quotas themselves are TASK-087.
Candidate card and versions:
- `Organization.candidate_card` is the card as a candidate sees it, built by the server from the profile and the level: the preview of PRD FR07. Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the question about the names of representatives below is decided. It repeats the profile fields and adds the level only; it has no membership, role, account, version, or basis. Its `representatives` is optional and nullable: absent or null means that they are not published, not that there are none. The invitation contract names the organization with `InvitationOrganization` and plans to return this card to the candidate additively.
- `version` starts at 1 and advances with every committed change of the profile. A change carries `expected_version` in the body for the reason the needs give: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for a stale version, as for needs. A body that changes nothing answers 200 with the current organization, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
- Order of the checks of `UpdateOrganization`: session (401), CSRF and Origin (403), request validation (400), account scenario (403), membership (404) and role (403), a body that changes nothing (200), the version (412), domain rules (400).
Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records (TASK-198), because the C4 scope needs both references at once and the ledger tests of TASK-062 and TASK-063 use synthetic organization identifiers. The application never deletes an organization.
Open questions for the product owner:
- Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization.
- Organizations per account (blocking for TASK-078 and TASK-087): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals are TASK-319. The owner must decide the limit, or accept the risk explicitly, before the quotas of TASK-087 are enforced and before `CreateOrganization` is opened to users.
- Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters.
- Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website.
Planned, additive: member invitations, listing, role changes, and removal (TASK-081 to TASK-085), the full role matrix (TASK-463), the verification processes and their history (TASK-086), the quotas by level (TASK-087), the card in the candidate's invitation, the number-of-organizations cap, and a sphere code.
No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests.
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
+66 -1
View File
@@ -14,7 +14,7 @@
## Соглашения контракта
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganizationNeed`, `CreateMySupportCase` и команды приглашений требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase` и команды приглашений требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
### Ошибки
@@ -483,6 +483,71 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Новый код problem не добавляется: контракт использует `validation_failed` и `unauthenticated`. `TestConsentSchemaValidationPrecedesImplementation`, `TestConsentAccessBeforeImplementation` и `TestConsentDTOsCarryNoHashSubjectOrContact` закрепляют сгенерированный сервер, а `frontend/src/shared/api/consent-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей хэша, субъекта и контактов.
### Организации
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (TASK-077, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в TASK-078 и TASK-079.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/organizations` | `ListMyOrganizations` | сессия | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
| `POST /api/v1/organizations` | `CreateOrganization` | сессия и CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 |
| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | сессия | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` |
| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | сессия и CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404, 412 `version_conflict`, 429 |
Каждая операция также объявляет problem-ответ `default`. Некорректный `org_id` отвечает 400 с указателем пути.
Активный контекст организации (решение TASK-077):
- Контекст не хранится на сервере. Каждая операция в области организации, включая потребности и приглашения этого контракта, называет организацию в пути `org_id`, а сервер на каждом запросе проверяет этот идентификатор по активному членству аккаунта сессии. Сам идентификатор ничего не дает; переключение между организациями - это другой `org_id` в маршрутах клиента.
- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (TASK-079 требует закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. TASK-085 очищает клиентские запросы с областью организации при переключении, что согласуется с клиентским контекстом.
- `ListMyOrganizations` - справочник контекстов: организации, где у вызывающего `active` членство, от нового членства к старому, с ролью и состоянием вызывающего. Клиент выбирает контекст из него, может помнить последний выбор в браузере для удобства и перечитывает список после 404 по пути организации. Человек с несколькими членствами видит все и работает в одной за раз; права и данные организаций остаются раздельными.
Доступ:
- Только аккаунт работодателя. Аккаунт кандидата получает 403 `forbidden` на всех четырех операциях, аккаунт без сессии - 401.
- `GetOrganization` и `UpdateOrganization` одинаково отвечают 404 `not_found` аккаунту без активного членства в `org_id` и на неизвестную организацию, а также участнику в состоянии `suspended`, `removed` или `left`, поэтому организации нельзя перечислить, а отозванный участник теряет следующее чтение сразу. Участник, чья роль не управляет организацией, получает 403 `forbidden` на `UpdateOrganization`; матрица FR07 отдает управление компанией и сотрудниками только владельцу. В MVP каждый участник - владелец, потому что операции добавления участников запланированы.
- `CreateOrganization` создает организацию и членство владельца для вызывающего в одной транзакции (роль `owner`, состояние `active`), поэтому организации без владельца не существует; база отказывается фиксировать такую. В теле нет поля владельца, роли, членства или уровня проверки.
Членства:
- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at` в TASK-082); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками (TASK-082, TASK-084), а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта.
- Роль живет только в членстве. В `Organization`, `OrganizationCreate`, `OrganizationUpdate` и `CandidateOrganizationCard` нет поля роли, владельца или участника. Свою роль вызывающий читает в `OrganizationMembership` из `ListMyOrganizations`; DTO не называет аккаунт.
- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает (TASK-081 и TASK-082). Человек может иметь независимые членства в нескольких организациях.
- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в TASK-083 и TASK-463. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в TASK-084 и TASK-085 и добавляют в контракт операции, а не поля.
Профиль:
- `OrganizationCreate` требует только `name`. Поля профиля: `name` (1-200 символов, без пробелов и переводов строки по краям, потому что запись согласия хранит его копию), `description` (1-2000 символов, nullable, переводы строки разрешены), `sphere` (1-100 символов, nullable, свободный текст: в PRD нет таксономии сферы, а код таксономии был бы аддитивным полем), `contacts` и `representatives`.
- `contacts` - один объект с `website`, `email`, `phone` и `telegram`, все обязательные и nullable, поэтому он одновременно поле запроса и сохраненное значение. Это публичные каналы компании: сайт по https без учетных данных, порта и IP-адреса, почта для вакансий, телефон в формате E.164 и имя пользователя Telegram с ведущим `@`. Личных контактов сотрудника в контракте нет, а сервер не отличает личный адрес от адреса компании, поэтому за содержимое отвечает владелец; жалоба на организацию подается через обращение в поддержку. Сервер никогда не обращается по адресу сайта.
- `representatives` - список до десяти записей `{name, job_title}` в порядке, заданном владельцем. Представитель существует только для показа: не участник, без связи с аккаунтом, без контакта и без прав, а участник не становится представителем при вступлении. Имя - персональные данные сотрудника, которые публикует владелец, отсюда открытый вопрос ниже.
- `UpdateOrganization` использует явную замену полей, как `UpdateOrganizationNeed`: присутствующее поле заменяет поле целиком, отсутствующее остается без изменений, а `contacts` и `representatives` никогда не объединяются. `description` и `sphere` со значением null становятся неустановленными; `name`, `contacts` и `representatives` не могут быть null. ogen генерирует `OptNil` для nullable-полей и обычный slice для `representatives`, где nil означает отсутствие, а `[]` - замену пустым списком; обработчик обязан проверять его через `!= nil`, а не через `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`).
- Текст простой: клиенты показывают каждое поле как текст, а не как HTML. Доменные правила, которым нужно больше, чем схема, например правила хоста сайта, отвечают 400 с указателем (`/contacts/website`, `/representatives/0/job_title`); формы показывают примеры.
Уровень проверки:
- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе.
- Ни один запрос не задает и не повышает уровень или его основание: `OrganizationCreate` и `OrganizationUpdate` - закрытые объекты только с полями профиля, ни одна операция контракта не меняет уровень, а правка описания, контактов или представителей оставляет его как есть. База держит уровень и основание в отдельных столбцах, которые оператор обновления профиля никогда не пишет, а CHECK связывает каждый уровень с его основаниями. `OrganizationVerification` только для чтения: `level`, `basis` и `changed_at`; область проверки и история изменений (FR07 в PRD) придут аддитивными полями с первым процессом.
- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Сами квоты - TASK-087.
Карточка кандидата и версии:
- `Organization.candidate_card` - карточка так, как ее видит кандидат; сервер строит ее из профиля и уровня: предпросмотр FR07 в PRD. Ее видит только кандидат, получивший приглашение от организации; это не публичная страница, и ни одна операция не показывает ее другим, пока не решен вопрос об именах представителей ниже. Она повторяет поля профиля и добавляет только уровень; в ней нет членства, роли, аккаунта, версии и основания. Ее `representatives` необязательно и допускает null: отсутствие или null означает, что представители не опубликованы, а не что их нет. Контракт приглашения называет организацию через `InvitationOrganization` и планирует аддитивно отдавать эту карточку кандидату.
- `version` начинается с 1 и растет с каждым зафиксированным изменением профиля. Изменение несет `expected_version` в теле по той же причине, что и потребности: сгенерированный клиент пока не читает `ETag`. Устаревшее значение отвечает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 для устаревшей версии, как и для потребностей. Тело без изменений отвечает 200 с текущей организацией, поэтому PATCH не нужен Idempotency-Key. POST нужен ключ с повтором на 24 часа; сохраняется только 201.
- Порядок проверок `UpdateOrganization`: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), членство (404) и роль (403), тело без изменений (200), версия (412), доменные правила (400).
Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений (TASK-198), потому что для области C4 нужны сразу обе ссылки, а тесты журнала TASK-062 и TASK-063 используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию.
Открытые вопросы к владельцу продукта:
- Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией.
- Организаций на аккаунт (блокирует TASK-078 и TASK-087): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений - TASK-319. Владелец продукта должен решить лимит или явно принять риск до того, как квоты TASK-087 начнут применяться и до того, как `CreateOrganization` откроют пользователям.
- Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров.
- Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта.
Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление (TASK-081 - TASK-085), полная матрица ролей (TASK-463), процессы проверки и их история (TASK-086), квоты по уровню (TASK-087), карточка в приглашении кандидата, ограничение числа организаций и код сферы.
Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах.
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
+199
View File
@@ -3580,3 +3580,202 @@ ConsentRecordListPage:
page:
has_more: false
next_cursor: null
OrganizationCreateNameOnly:
summary: A company that starts with its name only
description: Only the name is required; the card is completed later with UpdateOrganization.
value:
name: ООО Пример Платежи
OrganizationCreateCompleteCard:
summary: A company that gives its whole card at creation
description: Every contact is a company channel, and the representative is presentation only. There is no field for a role or a verification level.
value:
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: "+74950000000"
telegram: "@payments_careers"
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
OrganizationNameOnly:
summary: A new organization that has only a name
description: The creator is the owner of the organization, which starts at the verification level e0 on the ground of the confirmed email. The card repeats the profile as a candidate sees it.
value:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
version: 1
name: ООО Пример Платежи
description: null
sphere: null
contacts:
website: null
email: null
phone: null
telegram: null
representatives: []
verification:
level: e0
basis: confirmed_email
changed_at: "2026-10-06T09:00:00Z"
candidate_card:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
description: null
sphere: null
contacts:
website: null
email: null
phone: null
telegram: null
representatives: []
verification_level: e0
created_at: "2026-10-06T09:00:00Z"
updated_at: "2026-10-06T09:00:00Z"
OrganizationCompleteCard:
summary: An organization with a complete card, still at the level e0
description: Completing the card, adding contacts, and listing representatives did not raise the verification level, which stays e0 and changes only through a verification process of the server.
value:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
version: 2
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: "+74950000000"
telegram: "@payments_careers"
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
verification:
level: e0
basis: confirmed_email
changed_at: "2026-10-06T09:00:00Z"
candidate_card:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: "+74950000000"
telegram: "@payments_careers"
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
verification_level: e0
created_at: "2026-10-06T09:00:00Z"
updated_at: "2026-10-06T09:40:00Z"
OrganizationUpdateCompleteCard:
summary: The owner completes the card of the organization
description: The change carries the version that the client read and the fields to replace; contacts and representatives are replaced as a whole. The body has no role or verification field.
value:
expected_version: 1
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: "+74950000000"
telegram: "@payments_careers"
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
MyOrganizationListPage:
summary: The organizations of an owner who works in two companies
description: The caller has an active membership in both organizations, newest first. A third organization, where the caller left, is not listed.
value:
items:
- organization:
id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c
name: ИП Тестов Логистика
verification_level: e0
membership:
organization_id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c
role: owner
state: active
joined_at: "2026-10-06T11:30:00Z"
- organization:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
verification_level: e0
membership:
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
role: owner
state: active
joined_at: "2026-10-06T09:00:00Z"
page:
has_more: false
next_cursor: null
OrganizationUnknownField:
summary: The client sent a role together with the profile
description: A role, an owner, a verification level, and a list of members are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body.
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5c
errors:
- in: body
pointer: ""
code: invalid
message: The value does not match the contract.
OrganizationWebsiteNotHttps:
summary: The website is not an https URL of a host name
description: A domain rule of the server, checked after the schema. The schema already refuses a value that is not an https URL; the server also refuses a port, an IP address, and a host name without a dot.
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6d
errors:
- in: body
pointer: /contacts/website
code: invalid
message: The value does not match the contract.
OrganizationNameWithWhitespace:
summary: The name has leading whitespace
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 3a4b5c6d-7e8f-4a9b-8c1d-2e3f4a5b6c7e
errors:
- in: body
pointer: /name
code: invalid
message: The value does not match the contract.
OrganizationMissingExpectedVersion:
summary: A change without expected_version
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 4b5c6d7e-8f9a-4b0c-9d2e-3f4a5b6c7d8f
errors:
- in: body
pointer: /expected_version
code: required
message: The value is required.
OrganizationStaleVersion:
summary: The change carried a stale expected_version
description: Another member changed the organization after the client read it. Nothing was changed; the client reads the organization again and reapplies its edits.
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 5c6d7e8f-9a0b-4c1d-8e3f-4a5b6c7d8e90
+36
View File
@@ -554,3 +554,39 @@ InvitationCommandConflict:
$ref: ./examples.yml#/InvitationSendBlocked
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
OrganizationValidationFailed:
description: >-
The body does not match the contract or violates an organization rule:
a missing name, an unknown field such as role, verification_level,
verification, members, owner, or version, a name or sphere with
surrounding whitespace or a line break, a website that is not an https
URL of a host name, a phone number outside E.164, a Telegram username
without the leading @, a contact that has no valid form, more than ten
representatives, or a missing or invalid expected_version; code
validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the
outcome is not stored under an Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
role_sent_by_client:
$ref: ./examples.yml#/OrganizationUnknownField
website_not_https:
$ref: ./examples.yml#/OrganizationWebsiteNotHttps
name_with_surrounding_whitespace:
$ref: ./examples.yml#/OrganizationNameWithWhitespace
missing_expected_version:
$ref: ./examples.yml#/OrganizationMissingExpectedVersion
OrganizationVersionConflict:
description: >-
`expected_version` is not the current version of the organization; code
version_conflict. Nothing was changed; read the organization again
before retrying.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
version_conflict:
$ref: ./examples.yml#/OrganizationStaleVersion
+396 -1
View File
@@ -2378,7 +2378,7 @@ InvitationContactAccess:
$ref: '#/ContactFieldKind'
InvitationOrganization:
type: object
description: Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.
description: Organization that sent the invitation, as the candidate sees it before deciding. The card that a candidate sees is `CandidateOrganizationCard` of the organization contract; returning it with the invitation is planned as an additive field, and this object only names the organization.
additionalProperties: false
required:
- id
@@ -3754,6 +3754,401 @@ NeedUpdate:
oneOf:
- $ref: '#/NeedSalaryInput'
- type: 'null'
OrganizationVersion:
type: integer
format: int64
minimum: 1
description: 'Version of the profile of an organization. Creation makes version 1, and every committed change of the profile advances it by exactly one. A change carries the version the client read as `expected_version`. Only the profile has a version: the memberships and the verification level of the organization do not advance it.'
examples:
- 2
OrganizationName:
type: string
minLength: 1
maxLength: 200
pattern: ^\S(?:[^\n\r]*\S)?$
description: Public name of the organization, for example the legal name that a candidate knows. It has no leading or trailing whitespace and no line breaks, and it is at most 200 characters because consent records keep a copy of it. Plain text; clients show it as text, never as HTML. A later rename never changes the copy that a consent record holds.
examples:
- ООО Пример Платежи
OrganizationDescription:
type: string
minLength: 1
maxLength: 2000
description: What the organization does, written for candidates. It may contain line breaks; the server stores CRLF as LF, and it refuses leading and trailing whitespace and any other control character. Plain text; clients show it as text, never as HTML.
examples:
- Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
OrganizationSphere:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Field of business of the organization as free text, for example "Платежи и финансовые сервисы". It has no leading or trailing whitespace and no line breaks. The product has no sphere taxonomy yet; a taxonomy code would be an additive field. Plain text; clients show it as text, never as HTML.
examples:
- Платежи и финансовые сервисы
OrganizationWebsite:
type: string
minLength: 9
maxLength: 300
pattern: ^https://[^\s/?#@]+(?:[/?#][^\s]*)?$
description: 'Public website of the organization: an https URL with a host name, without credentials. The server also refuses a port, an IP address, a host name without a dot, and `localhost`. It never fetches the address.'
examples:
- https://payments.example.com
OrganizationContactChannels:
type: object
description: Public contacts of the organization, the ones a candidate sees on its card. They are company channels, such as a careers mailbox, the website, a company phone, or a company Telegram account, and never the personal email address, phone, or messenger of an employee; personal contacts of the people of the organization stay out of this object. The server cannot tell a company address from a personal one, so the owner answers for the content, and a candidate can complain about an organization through a support case. The object is the request field and the stored value alike, so a response can be sent back unchanged; every field is required and null means not set. A change replaces the whole object, never a single field of it.
additionalProperties: false
required:
- website
- email
- phone
- telegram
properties:
website:
oneOf:
- $ref: '#/OrganizationWebsite'
- type: 'null'
email:
description: Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.
oneOf:
- $ref: '#/EmailAddress'
- type: 'null'
phone:
description: Public phone number of the organization, or null.
oneOf:
- $ref: '#/ContactPhoneNumber'
- type: 'null'
telegram:
description: Public Telegram account of the organization, or null.
oneOf:
- $ref: '#/ContactTelegramUsername'
- type: 'null'
OrganizationRepresentative:
type: object
description: 'A person that speaks for the organization to candidates, as the owner presents them on the card. It is presentation only: a representative is not a member of the organization, has no account link, and gains no right from being listed, and a member does not become a representative by joining. It holds no contact of the person; reaching the organization goes through its public contacts. The name is personal data of an employee that the owner publishes, so the owner must have the right to do it; see the open questions in the organization section of the API guide.'
additionalProperties: false
required:
- name
- job_title
properties:
name:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Name of the person as the card shows it. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
job_title:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Position of the person in the organization, for example "Руководитель по подбору". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
OrganizationVerificationLevel:
type: string
description: 'Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate.
- e0: the confirmed email of the account that created the organization. Every new organization starts here.
- e1: a corporate email, a verified domain, and a link with the organization.
- e2: a check of the requisites and of the authority of the person.
- e3: a manual check or a partner status.
The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change.'
enum:
- e0
- e1
- e2
- e3
OrganizationVerificationBasis:
type: string
description: 'Ground of the current verification level, the reason a cabinet can show next to it.
- confirmed_email: the confirmed email of the creating account (e0).
- corporate_domain: a corporate email and a verified domain (e1).
- requisites_and_authority: a check of the requisites and of the authority (e2).
- manual_review: a manual check by the platform (e3).
- partner_status: a partner status (e3).
Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change.'
enum:
- confirmed_email
- corporate_domain
- requisites_and_authority
- manual_review
- partner_status
OrganizationVerification:
type: object
description: 'Verification level of an organization with its ground and the time it was set. It is read-only everywhere in this contract: the server sets it, and no request carries it. The scope of the check and the history of changes (PRD FR07) are planned as additive fields and a separate history with the first verification process.'
additionalProperties: false
required:
- level
- basis
- changed_at
properties:
level:
$ref: '#/OrganizationVerificationLevel'
basis:
$ref: '#/OrganizationVerificationBasis'
changed_at:
description: Moment the level was set to its current value; for a new organization, the creation time.
allOf:
- $ref: '#/Timestamp'
CandidateOrganizationCard:
type: object
description: 'The card of an organization as a candidate sees it: what an invitation shows before the candidate decides. The server builds it from the profile and the verification level and returns it to the owner as the preview of PRD FR07 ("through the eyes of the candidate"); a client never sends it. It holds no membership, no role, no account, no version, and no ground of the verification: a member''s email address, the number of members, and the history of the organization stay out of it. The card is the same object that the candidate side will return (planned in the invitation contract). Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the open question about publishing the names of representatives is decided (152-FZ). The server may leave `representatives` out, and a card without them means that the representatives are not published, not that the organization has none.'
additionalProperties: false
required:
- id
- name
- description
- sphere
- contacts
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization.
name:
$ref: '#/OrganizationName'
description:
description: Description of the organization, or null.
oneOf:
- $ref: '#/OrganizationDescription'
- type: 'null'
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: '#/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/OrganizationContactChannels'
representatives:
type:
- array
- 'null'
maxItems: 10
description: Representatives in the order the owner gave them. Absent or null means that they are not published on this card, which says nothing about whether the organization has any.
items:
$ref: '#/OrganizationRepresentative'
verification_level:
$ref: '#/OrganizationVerificationLevel'
Organization:
type: object
description: 'Organization as its members read it: the profile that the owner edits, the verification level that only the server sets, and the card that a candidate sees. It never contains a role, a membership, the members of the organization, or an account identifier, so no field of it can raise a right: the role of the caller is in `OrganizationMembership` and comes only from the membership held by the server. The profile fields repeat in `candidate_card`, which is the candidate''s view of them; the client reads the profile fields for the form and `candidate_card` for the preview.'
additionalProperties: false
required:
- id
- version
- name
- description
- sphere
- contacts
- representatives
- verification
- candidate_card
- created_at
- updated_at
properties:
id:
type: string
format: uuid
description: Identifier of the organization, the `org_id` of every organization-scoped path. It never changes.
version:
$ref: '#/OrganizationVersion'
name:
$ref: '#/OrganizationName'
description:
description: Description of the organization, or null.
oneOf:
- $ref: '#/OrganizationDescription'
- type: 'null'
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: '#/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
description: Representatives in the order the owner gave them.
items:
$ref: '#/OrganizationRepresentative'
verification:
$ref: '#/OrganizationVerification'
candidate_card:
$ref: '#/CandidateOrganizationCard'
created_at:
$ref: '#/Timestamp'
updated_at:
$ref: '#/Timestamp'
OrganizationCreate:
type: object
description: New organization. Only `name` is required, so a company can start with its name and complete the card later. The creating account becomes the owner of the organization; the body has no field for a role, a membership, an owner, a verification level, or a version, and unknown fields are rejected, so a request cannot set any of them. An absent `description` or `sphere`, and one sent as null, stay unset; an absent `contacts` has every contact unset; an absent `representatives` is an empty list.
additionalProperties: false
required:
- name
properties:
name:
$ref: '#/OrganizationName'
description:
oneOf:
- $ref: '#/OrganizationDescription'
- type: 'null'
sphere:
oneOf:
- $ref: '#/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
items:
$ref: '#/OrganizationRepresentative'
OrganizationUpdate:
type: object
description: Change of the profile of an organization over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged, and a representative left out of a sent list is removed. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. The body can change the profile only. It has no field for a role, a membership, an owner, a verification level, a basis, or a card, and unknown fields are rejected, so editing the profile can neither raise a right nor raise the trust level of the organization; both change only through processes of the server.
additionalProperties: false
required:
- expected_version
properties:
expected_version:
$ref: '#/OrganizationVersion'
name:
$ref: '#/OrganizationName'
description:
oneOf:
- $ref: '#/OrganizationDescription'
- type: 'null'
sphere:
oneOf:
- $ref: '#/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
items:
$ref: '#/OrganizationRepresentative'
OrganizationRole:
type: string
description: 'Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.
- owner: manages the organization and its members, and acts on behalf of the company.
- recruiter: leads the selection of candidates for all needs.
- hiring_manager: acts on the needs assigned to the member.
- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.
In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.'
enum:
- owner
- recruiter
- hiring_manager
- technical_expert
MembershipState:
type: string
description: 'State of a membership. Only `active` gives access: every other state answers as if the account were no member.
- active: the member works in the organization with the role.
- suspended: access is stopped, and the owner or the platform may restore it.
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
- left: the member ended the membership.
One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'
enum:
- active
- suspended
- removed
- left
OrganizationMembership:
type: object
description: The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them.
additionalProperties: false
required:
- organization_id
- role
- state
- joined_at
properties:
organization_id:
type: string
format: uuid
description: Identifier of the organization.
role:
$ref: '#/OrganizationRole'
state:
$ref: '#/MembershipState'
joined_at:
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).
allOf:
- $ref: '#/Timestamp'
OrganizationSummary:
type: object
description: 'An organization in the list of the caller''s organizations: what a switcher needs to name it. The profile, the contacts, and the representatives are in `Organization`.'
additionalProperties: false
required:
- id
- name
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization, the `org_id` of its paths.
name:
$ref: '#/OrganizationName'
verification_level:
$ref: '#/OrganizationVerificationLevel'
MyOrganization:
type: object
description: An organization available to the caller together with the caller's membership in it.
additionalProperties: false
required:
- organization
- membership
properties:
organization:
$ref: '#/OrganizationSummary'
membership:
$ref: '#/OrganizationMembership'
MyOrganizationList:
type: object
description: One page of the organizations available to the caller, newest membership first. It holds only organizations where the caller has an `active` membership, so it is also the list of contexts the caller can work in; it never names an organization the caller cannot enter.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Organizations of the page.
items:
$ref: '#/MyOrganization'
page:
$ref: '#/PageInfo'
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
@@ -404,8 +404,9 @@ schemas:
type: object
description: >-
Organization that sent the invitation, as the candidate sees it before
deciding. The organization contract (TASK-077) adds the public card;
this object only names it.
deciding. The card that a candidate sees is `CandidateOrganizationCard` of
the organization contract; returning it with the invitation is planned
as an additive field, and this object only names the organization.
additionalProperties: false
required:
- id
@@ -0,0 +1,503 @@
schemas:
OrganizationVersion:
type: integer
format: int64
minimum: 1
description: >-
Version of the profile of an organization. Creation makes version 1,
and every committed change of the profile advances it by exactly one.
A change carries the version the client read as `expected_version`.
Only the profile has a version: the memberships and the verification
level of the organization do not advance it.
examples:
- 2
OrganizationName:
type: string
minLength: 1
maxLength: 200
pattern: '^\S(?:[^\n\r]*\S)?$'
description: >-
Public name of the organization, for example the legal name that a
candidate knows. It has no leading or trailing whitespace and no line
breaks, and it is at most 200 characters because consent records keep
a copy of it. Plain text; clients show it as text, never as HTML. A
later rename never changes the copy that a consent record holds.
examples:
- ООО Пример Платежи
OrganizationDescription:
type: string
minLength: 1
maxLength: 2000
description: >-
What the organization does, written for candidates. It may contain
line breaks; the server stores CRLF as LF, and it refuses leading and
trailing whitespace and any other control character. Plain text;
clients show it as text, never as HTML.
examples:
- Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
OrganizationSphere:
type: string
minLength: 1
maxLength: 100
pattern: '^\S(?:.*\S)?$'
description: >-
Field of business of the organization as free text, for example
"Платежи и финансовые сервисы". It has no leading or trailing
whitespace and no line breaks. The product has no sphere taxonomy
yet; a taxonomy code would be an additive field. Plain text; clients
show it as text, never as HTML.
examples:
- Платежи и финансовые сервисы
OrganizationWebsite:
type: string
minLength: 9
maxLength: 300
pattern: '^https://[^\s/?#@]+(?:[/?#][^\s]*)?$'
description: >-
Public website of the organization: an https URL with a host name,
without credentials. The server also refuses a port, an IP address, a
host name without a dot, and `localhost`. It never fetches the
address.
examples:
- https://payments.example.com
OrganizationContactChannels:
type: object
description: >-
Public contacts of the organization, the ones a candidate sees on its
card. They are company channels, such as a careers mailbox, the
website, a company phone, or a company Telegram account, and never the
personal email address, phone, or messenger of an employee; personal
contacts of the people of the organization stay out of this object.
The server cannot tell a company address from a personal one, so the
owner answers for the content, and a candidate can complain about an
organization through a support case. The object is the request field
and the stored value alike, so a response can be sent back unchanged;
every field is required and null means not set. A change replaces the
whole object, never a single field of it.
additionalProperties: false
required:
- website
- email
- phone
- telegram
properties:
website:
oneOf:
- $ref: "#/schemas/OrganizationWebsite"
- type: "null"
email:
description: >-
Public mailbox of the organization, such as a careers address, or
null. It is stored in the form it was given.
oneOf:
- $ref: "./identity_schemas.yml#/schemas/EmailAddress"
- type: "null"
phone:
description: Public phone number of the organization, or null.
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber"
- type: "null"
telegram:
description: Public Telegram account of the organization, or null.
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername"
- type: "null"
OrganizationRepresentative:
type: object
description: >-
A person that speaks for the organization to candidates, as the
owner presents them on the card. It is presentation only: a
representative is not a member of the organization, has no account
link, and gains no right from being listed, and a member does not
become a representative by joining. It holds no contact of the
person; reaching the organization goes through its public contacts.
The name is personal data of an employee that the owner publishes, so
the owner must have the right to do it; see the open questions in the
organization section of the API guide.
additionalProperties: false
required:
- name
- job_title
properties:
name:
type: string
minLength: 1
maxLength: 100
pattern: '^\S(?:.*\S)?$'
description: >-
Name of the person as the card shows it. It has no leading or
trailing whitespace and no line breaks. Plain text; clients show
it as text, never as HTML.
job_title:
type: string
minLength: 1
maxLength: 100
pattern: '^\S(?:.*\S)?$'
description: >-
Position of the person in the organization, for example "Руководитель
по подбору". It has no leading or trailing whitespace and no line
breaks. Plain text; clients show it as text, never as HTML.
OrganizationVerificationLevel:
type: string
description: |-
Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate.
- e0: the confirmed email of the account that created the organization. Every new organization starts here.
- e1: a corporate email, a verified domain, and a link with the organization.
- e2: a check of the requisites and of the authority of the person.
- e3: a manual check or a partner status.
The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change.
enum:
- e0
- e1
- e2
- e3
OrganizationVerificationBasis:
type: string
description: |-
Ground of the current verification level, the reason a cabinet can show next to it.
- confirmed_email: the confirmed email of the creating account (e0).
- corporate_domain: a corporate email and a verified domain (e1).
- requisites_and_authority: a check of the requisites and of the authority (e2).
- manual_review: a manual check by the platform (e3).
- partner_status: a partner status (e3).
Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change.
enum:
- confirmed_email
- corporate_domain
- requisites_and_authority
- manual_review
- partner_status
OrganizationVerification:
type: object
description: >-
Verification level of an organization with its ground and the time it
was set. It is read-only everywhere in this contract: the server sets
it, and no request carries it. The scope of the check and the history
of changes (PRD FR07) are planned as additive fields and a separate
history with the first verification process.
additionalProperties: false
required:
- level
- basis
- changed_at
properties:
level:
$ref: "#/schemas/OrganizationVerificationLevel"
basis:
$ref: "#/schemas/OrganizationVerificationBasis"
changed_at:
description: >-
Moment the level was set to its current value; for a new
organization, the creation time.
allOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
CandidateOrganizationCard:
type: object
description: >-
The card of an organization as a candidate sees it: what an invitation
shows before the candidate decides. The server builds it from the
profile and the verification level and returns it to the owner as the
preview of PRD FR07 ("through the eyes of the candidate"); a client
never sends it. It holds no membership, no role, no account, no
version, and no ground of the verification: a member's email address,
the number of members, and the history of the organization stay out of
it. The card is the same object that the candidate side will return
(planned in the invitation contract). Only a candidate who received an
invitation from the organization sees it; it is not a public page, and
no operation shows it to anyone else until the open question about
publishing the names of representatives is decided (152-FZ). The
server may leave `representatives` out, and a card without them means
that the representatives are not published, not that the organization
has none.
additionalProperties: false
required:
- id
- name
- description
- sphere
- contacts
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization.
name:
$ref: "#/schemas/OrganizationName"
description:
description: Description of the organization, or null.
oneOf:
- $ref: "#/schemas/OrganizationDescription"
- type: "null"
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: "#/schemas/OrganizationSphere"
- type: "null"
contacts:
$ref: "#/schemas/OrganizationContactChannels"
representatives:
type:
- array
- "null"
maxItems: 10
description: >-
Representatives in the order the owner gave them. Absent or null
means that they are not published on this card, which says nothing
about whether the organization has any.
items:
$ref: "#/schemas/OrganizationRepresentative"
verification_level:
$ref: "#/schemas/OrganizationVerificationLevel"
Organization:
type: object
description: >-
Organization as its members read it: the profile that the owner edits,
the verification level that only the server sets, and the card that a
candidate sees. It never contains a role, a membership, the members
of the organization, or an account identifier, so no field of it can
raise a right: the role of the caller is in `OrganizationMembership`
and comes only from the membership held by the server. The profile
fields repeat in `candidate_card`, which is the candidate's view of
them; the client reads the profile fields for the form and
`candidate_card` for the preview.
additionalProperties: false
required:
- id
- version
- name
- description
- sphere
- contacts
- representatives
- verification
- candidate_card
- created_at
- updated_at
properties:
id:
type: string
format: uuid
description: >-
Identifier of the organization, the `org_id` of every
organization-scoped path. It never changes.
version:
$ref: "#/schemas/OrganizationVersion"
name:
$ref: "#/schemas/OrganizationName"
description:
description: Description of the organization, or null.
oneOf:
- $ref: "#/schemas/OrganizationDescription"
- type: "null"
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: "#/schemas/OrganizationSphere"
- type: "null"
contacts:
$ref: "#/schemas/OrganizationContactChannels"
representatives:
type: array
maxItems: 10
description: Representatives in the order the owner gave them.
items:
$ref: "#/schemas/OrganizationRepresentative"
verification:
$ref: "#/schemas/OrganizationVerification"
candidate_card:
$ref: "#/schemas/CandidateOrganizationCard"
created_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
updated_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
OrganizationCreate:
type: object
description: >-
New organization. Only `name` is required, so a company can start with
its name and complete the card later. The creating account becomes the
owner of the organization; the body has no field for a role, a
membership, an owner, a verification level, or a version, and unknown
fields are rejected, so a request cannot set any of them. An absent
`description` or `sphere`, and one sent as null, stay unset; an absent
`contacts` has every contact unset; an absent `representatives` is an
empty list.
additionalProperties: false
required:
- name
properties:
name:
$ref: "#/schemas/OrganizationName"
description:
oneOf:
- $ref: "#/schemas/OrganizationDescription"
- type: "null"
sphere:
oneOf:
- $ref: "#/schemas/OrganizationSphere"
- type: "null"
contacts:
$ref: "#/schemas/OrganizationContactChannels"
representatives:
type: array
maxItems: 10
items:
$ref: "#/schemas/OrganizationRepresentative"
OrganizationUpdate:
type: object
description: >-
Change of the profile of an organization over the version the client
read. Each field present replaces that field as a whole and an absent
field stays unchanged; `contacts` and `representatives` are replaced
entirely and never merged, and a representative left out of a sent
list is removed. `description` and `sphere` sent as null become unset;
`name`, `contacts`, and `representatives` cannot be null. The body can
change the profile only. It has no field for a role, a membership, an
owner, a verification level, a basis, or a card, and unknown fields
are rejected, so editing the profile can neither raise a right nor
raise the trust level of the organization; both change only through
processes of the server.
additionalProperties: false
required:
- expected_version
properties:
expected_version:
$ref: "#/schemas/OrganizationVersion"
name:
$ref: "#/schemas/OrganizationName"
description:
oneOf:
- $ref: "#/schemas/OrganizationDescription"
- type: "null"
sphere:
oneOf:
- $ref: "#/schemas/OrganizationSphere"
- type: "null"
contacts:
$ref: "#/schemas/OrganizationContactChannels"
representatives:
type: array
maxItems: 10
items:
$ref: "#/schemas/OrganizationRepresentative"
OrganizationRole:
type: string
description: |-
Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.
- owner: manages the organization and its members, and acts on behalf of the company.
- recruiter: leads the selection of candidates for all needs.
- hiring_manager: acts on the needs assigned to the member.
- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.
In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.
enum:
- owner
- recruiter
- hiring_manager
- technical_expert
MembershipState:
type: string
description: |-
State of a membership. Only `active` gives access: every other state answers as if the account were no member.
- active: the member works in the organization with the role.
- suspended: access is stopped, and the owner or the platform may restore it.
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
- left: the member ended the membership.
One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.
enum:
- active
- suspended
- removed
- left
OrganizationMembership:
type: object
description: >-
The membership of the caller in one organization. The caller is the
account of the session, so the object holds no account identifier.
Only the server sets the role and the state, through the operations
that manage members, which are planned; no operation of this contract
changes them.
additionalProperties: false
required:
- organization_id
- role
- state
- joined_at
properties:
organization_id:
type: string
format: uuid
description: Identifier of the organization.
role:
$ref: "#/schemas/OrganizationRole"
state:
$ref: "#/schemas/MembershipState"
joined_at:
description: >-
Moment the membership was first created. A member who left and
returns keeps the same value, because the pair has one membership;
the moment of the latest activation is a planned additive field
(`activated_at`, TASK-082).
allOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
OrganizationSummary:
type: object
description: >-
An organization in the list of the caller's organizations: what a
switcher needs to name it. The profile, the contacts, and the
representatives are in `Organization`.
additionalProperties: false
required:
- id
- name
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization, the `org_id` of its paths.
name:
$ref: "#/schemas/OrganizationName"
verification_level:
$ref: "#/schemas/OrganizationVerificationLevel"
MyOrganization:
type: object
description: >-
An organization available to the caller together with the caller's
membership in it.
additionalProperties: false
required:
- organization
- membership
properties:
organization:
$ref: "#/schemas/OrganizationSummary"
membership:
$ref: "#/schemas/OrganizationMembership"
MyOrganizationList:
type: object
description: >-
One page of the organizations available to the caller, newest
membership first. It holds only organizations where the caller has an
`active` membership, so it is also the list of contexts the caller can
work in; it never names an organization the caller cannot enter.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Organizations of the page.
items:
$ref: "#/schemas/MyOrganization"
page:
$ref: "./common_schemas.yml#/schemas/PageInfo"
+802 -1
View File
@@ -17,6 +17,8 @@ tags:
description: Data of the current candidate, such as the questionnaire with the chosen specializations and self-assessed grades. Confirmed grades and categories come only from assessment results.
- name: assessment
description: 'Assessment attempts of the current candidate: availability, start and resume, answers and the code practice, finalization, and the result. Answers, keys, and attempt history are visible only to the candidate.'
- name: organization
description: 'Organizations of employer accounts: the profile with its contacts and representatives, the verification level that only the server sets, and the memberships that give an account its role in an organization. The organization in the path is authoritative and is checked against an active membership on every request; no body carries a role, a membership, or a verification level.'
- name: need
description: 'Hiring needs of an organization: requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. Access comes only from an active membership in the organization; a need never requires a vacancy.'
- name: invitation
@@ -826,6 +828,204 @@ paths:
$ref: '#/components/responses/AssessmentResultNotReady'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/organizations:
get:
operationId: ListMyOrganizations
summary: List the organizations available to the current account.
description: |-
Requires the session cookie of an employer account. The account comes from the session, never from a request parameter, so the response holds only the caller's own memberships and no request can name another account.
Returns a page of the organizations in which the caller has an `active` membership, newest membership first with the organization identifier as the tie-breaker, with cursor pagination. Each item names the organization (`OrganizationSummary`) and holds the caller's role and state in it (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not list its organization, so an organization the caller cannot enter is never named, and one that the caller was removed from disappears from the list at once.
The list is the directory of the active organization context. The context is not stored on the server: every organization-scoped operation names its organization in the path `org_id`, and the server checks that identifier against the caller's active membership on every request, so a switch between organizations is a different `org_id` in the client's routes and cannot outlive a revoked membership. A client picks the context from this list, may remember the last choice in the browser as a convenience, and must read the list again after any answer 404 `not_found` from an organization path. An account with several memberships sees all of them here and works in one at a time; the rights and the data of the organizations stay separate.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden. An employer account without an organization gets an empty page, which tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 validation_failed.
security:
- sessionCookie: []
tags:
- organization
parameters:
- $ref: '#/components/parameters/PageLimit'
- $ref: '#/components/parameters/PageCursor'
responses:
'200':
description: A page of the organizations available to the current account.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/MyOrganizationList'
examples:
one_organization:
$ref: '#/components/examples/MyOrganizationListPage'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
default:
$ref: '#/components/responses/Problem'
/api/v1/organizations:
post:
operationId: CreateOrganization
summary: Create an organization; the caller becomes its owner.
description: |-
Requires the session cookie of an employer account with a confirmed email, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the session: the body has no owner, membership, role, verification, or version field, and unknown fields fail validation.
The server creates the organization and the owner membership of the caller (role `owner`, state `active`) in one transaction, so an organization never exists without its owner. The organization starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be requested: the creator of a company with a corporate domain, a long description, or many representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of the server that do not exist yet. Only `name` is required; the rest of the card can be completed with UpdateOrganization.
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second organization. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. Two requests with different keys are two organizations; the product may limit the number of organizations per account (open question), which would answer 409 `state_conflict` without a change of the schema.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- organization
parameters:
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OrganizationCreate'
examples:
name_only:
$ref: '#/components/examples/OrganizationCreateNameOnly'
complete_card:
$ref: '#/components/examples/OrganizationCreateCompleteCard'
responses:
'201':
description: The organization was created with the caller as its owner, or a retry with the same Idempotency-Key replayed its creation.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/Organization'
examples:
name_only:
$ref: '#/components/examples/OrganizationNameOnly'
complete_card:
$ref: '#/components/examples/OrganizationCompleteCard'
'400':
$ref: '#/components/responses/OrganizationValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'409':
$ref: '#/components/responses/IdempotencyInProgress'
'422':
$ref: '#/components/responses/UnprocessableContent'
'429':
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/organizations/{org_id}:
get:
operationId: GetOrganization
summary: Read an organization of which the caller is a member.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
- organization
parameters:
- $ref: '#/components/parameters/OrganizationId'
responses:
'200':
description: The organization.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/Organization'
examples:
name_only:
$ref: '#/components/examples/OrganizationNameOnly'
complete_card:
$ref: '#/components/examples/OrganizationCompleteCard'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
'404':
$ref: '#/components/responses/NotFound'
default:
$ref: '#/components/responses/Problem'
patch:
operationId: UpdateOrganization
summary: Change the profile of an organization.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the organization (the FR07 matrix gives this to no other role), so a member with another role answers 403 forbidden. The role comes from the server-side membership; the body has no organization, membership, role, owner, or verification field.
Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null.
The body can change the profile only. The verification level, its basis, the card, the members, and every role are not fields of it, and unknown fields fail validation, so the owner can neither raise the trust level of the organization nor the rights of anyone by editing the profile; a longer description, a verified-looking website, or a new representative leaves the level unchanged. The level and the roles change only through processes of the server.
Versions: every committed change creates version `expected_version + 1` and answers 200 with the organization. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the organization again and reapplies its edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for needs. A body that changes nothing when applied to the current profile keeps the version and answers 200 with the current organization even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a change that already succeeded is harmless.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can answer 429 with Retry-After before any check.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- organization
parameters:
- $ref: '#/components/parameters/OrganizationId'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OrganizationUpdate'
examples:
complete_card:
$ref: '#/components/examples/OrganizationUpdateCompleteCard'
responses:
'200':
description: The organization after the change, or the current organization when the body changes nothing.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/Organization'
examples:
complete_card:
$ref: '#/components/examples/OrganizationCompleteCard'
'400':
$ref: '#/components/responses/OrganizationValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'404':
$ref: '#/components/responses/NotFound'
'412':
$ref: '#/components/responses/OrganizationVersionConflict'
'429':
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/organizations/{org_id}/needs:
get:
operationId: ListOrganizationNeeds
@@ -5600,7 +5800,7 @@ components:
$ref: '#/components/schemas/ContactFieldKind'
InvitationOrganization:
type: object
description: Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.
description: Organization that sent the invitation, as the candidate sees it before deciding. The card that a candidate sees is `CandidateOrganizationCard` of the organization contract; returning it with the invitation is planned as an additive field, and this object only names the organization.
additionalProperties: false
required:
- id
@@ -6441,6 +6641,384 @@ components:
$ref: '#/components/schemas/ConsentRecord'
page:
$ref: '#/components/schemas/PageInfo'
OrganizationVersion:
type: integer
format: int64
minimum: 1
description: 'Version of the profile of an organization. Creation makes version 1, and every committed change of the profile advances it by exactly one. A change carries the version the client read as `expected_version`. Only the profile has a version: the memberships and the verification level of the organization do not advance it.'
examples:
- 2
OrganizationName:
type: string
minLength: 1
maxLength: 200
pattern: ^\S(?:[^\n\r]*\S)?$
description: Public name of the organization, for example the legal name that a candidate knows. It has no leading or trailing whitespace and no line breaks, and it is at most 200 characters because consent records keep a copy of it. Plain text; clients show it as text, never as HTML. A later rename never changes the copy that a consent record holds.
examples:
- ООО Пример Платежи
OrganizationDescription:
type: string
minLength: 1
maxLength: 2000
description: What the organization does, written for candidates. It may contain line breaks; the server stores CRLF as LF, and it refuses leading and trailing whitespace and any other control character. Plain text; clients show it as text, never as HTML.
examples:
- Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
OrganizationSphere:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Field of business of the organization as free text, for example "Платежи и финансовые сервисы". It has no leading or trailing whitespace and no line breaks. The product has no sphere taxonomy yet; a taxonomy code would be an additive field. Plain text; clients show it as text, never as HTML.
examples:
- Платежи и финансовые сервисы
OrganizationWebsite:
type: string
minLength: 9
maxLength: 300
pattern: ^https://[^\s/?#@]+(?:[/?#][^\s]*)?$
description: 'Public website of the organization: an https URL with a host name, without credentials. The server also refuses a port, an IP address, a host name without a dot, and `localhost`. It never fetches the address.'
examples:
- https://payments.example.com
OrganizationContactChannels:
type: object
description: Public contacts of the organization, the ones a candidate sees on its card. They are company channels, such as a careers mailbox, the website, a company phone, or a company Telegram account, and never the personal email address, phone, or messenger of an employee; personal contacts of the people of the organization stay out of this object. The server cannot tell a company address from a personal one, so the owner answers for the content, and a candidate can complain about an organization through a support case. The object is the request field and the stored value alike, so a response can be sent back unchanged; every field is required and null means not set. A change replaces the whole object, never a single field of it.
additionalProperties: false
required:
- website
- email
- phone
- telegram
properties:
website:
oneOf:
- $ref: '#/components/schemas/OrganizationWebsite'
- type: 'null'
email:
description: Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.
oneOf:
- $ref: '#/components/schemas/EmailAddress'
- type: 'null'
phone:
description: Public phone number of the organization, or null.
oneOf:
- $ref: '#/components/schemas/ContactPhoneNumber'
- type: 'null'
telegram:
description: Public Telegram account of the organization, or null.
oneOf:
- $ref: '#/components/schemas/ContactTelegramUsername'
- type: 'null'
OrganizationRepresentative:
type: object
description: 'A person that speaks for the organization to candidates, as the owner presents them on the card. It is presentation only: a representative is not a member of the organization, has no account link, and gains no right from being listed, and a member does not become a representative by joining. It holds no contact of the person; reaching the organization goes through its public contacts. The name is personal data of an employee that the owner publishes, so the owner must have the right to do it; see the open questions in the organization section of the API guide.'
additionalProperties: false
required:
- name
- job_title
properties:
name:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Name of the person as the card shows it. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
job_title:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Position of the person in the organization, for example "Руководитель по подбору". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
OrganizationVerificationLevel:
type: string
description: |-
Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate.
- e0: the confirmed email of the account that created the organization. Every new organization starts here.
- e1: a corporate email, a verified domain, and a link with the organization.
- e2: a check of the requisites and of the authority of the person.
- e3: a manual check or a partner status.
The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change.
enum:
- e0
- e1
- e2
- e3
OrganizationVerificationBasis:
type: string
description: |-
Ground of the current verification level, the reason a cabinet can show next to it.
- confirmed_email: the confirmed email of the creating account (e0).
- corporate_domain: a corporate email and a verified domain (e1).
- requisites_and_authority: a check of the requisites and of the authority (e2).
- manual_review: a manual check by the platform (e3).
- partner_status: a partner status (e3).
Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change.
enum:
- confirmed_email
- corporate_domain
- requisites_and_authority
- manual_review
- partner_status
OrganizationVerification:
type: object
description: 'Verification level of an organization with its ground and the time it was set. It is read-only everywhere in this contract: the server sets it, and no request carries it. The scope of the check and the history of changes (PRD FR07) are planned as additive fields and a separate history with the first verification process.'
additionalProperties: false
required:
- level
- basis
- changed_at
properties:
level:
$ref: '#/components/schemas/OrganizationVerificationLevel'
basis:
$ref: '#/components/schemas/OrganizationVerificationBasis'
changed_at:
description: Moment the level was set to its current value; for a new organization, the creation time.
allOf:
- $ref: '#/components/schemas/Timestamp'
CandidateOrganizationCard:
type: object
description: 'The card of an organization as a candidate sees it: what an invitation shows before the candidate decides. The server builds it from the profile and the verification level and returns it to the owner as the preview of PRD FR07 ("through the eyes of the candidate"); a client never sends it. It holds no membership, no role, no account, no version, and no ground of the verification: a member''s email address, the number of members, and the history of the organization stay out of it. The card is the same object that the candidate side will return (planned in the invitation contract). Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the open question about publishing the names of representatives is decided (152-FZ). The server may leave `representatives` out, and a card without them means that the representatives are not published, not that the organization has none.'
additionalProperties: false
required:
- id
- name
- description
- sphere
- contacts
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization.
name:
$ref: '#/components/schemas/OrganizationName'
description:
description: Description of the organization, or null.
oneOf:
- $ref: '#/components/schemas/OrganizationDescription'
- type: 'null'
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: '#/components/schemas/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/components/schemas/OrganizationContactChannels'
representatives:
type:
- array
- 'null'
maxItems: 10
description: Representatives in the order the owner gave them. Absent or null means that they are not published on this card, which says nothing about whether the organization has any.
items:
$ref: '#/components/schemas/OrganizationRepresentative'
verification_level:
$ref: '#/components/schemas/OrganizationVerificationLevel'
Organization:
type: object
description: 'Organization as its members read it: the profile that the owner edits, the verification level that only the server sets, and the card that a candidate sees. It never contains a role, a membership, the members of the organization, or an account identifier, so no field of it can raise a right: the role of the caller is in `OrganizationMembership` and comes only from the membership held by the server. The profile fields repeat in `candidate_card`, which is the candidate''s view of them; the client reads the profile fields for the form and `candidate_card` for the preview.'
additionalProperties: false
required:
- id
- version
- name
- description
- sphere
- contacts
- representatives
- verification
- candidate_card
- created_at
- updated_at
properties:
id:
type: string
format: uuid
description: Identifier of the organization, the `org_id` of every organization-scoped path. It never changes.
version:
$ref: '#/components/schemas/OrganizationVersion'
name:
$ref: '#/components/schemas/OrganizationName'
description:
description: Description of the organization, or null.
oneOf:
- $ref: '#/components/schemas/OrganizationDescription'
- type: 'null'
sphere:
description: Field of business of the organization, or null.
oneOf:
- $ref: '#/components/schemas/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/components/schemas/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
description: Representatives in the order the owner gave them.
items:
$ref: '#/components/schemas/OrganizationRepresentative'
verification:
$ref: '#/components/schemas/OrganizationVerification'
candidate_card:
$ref: '#/components/schemas/CandidateOrganizationCard'
created_at:
$ref: '#/components/schemas/Timestamp'
updated_at:
$ref: '#/components/schemas/Timestamp'
OrganizationCreate:
type: object
description: New organization. Only `name` is required, so a company can start with its name and complete the card later. The creating account becomes the owner of the organization; the body has no field for a role, a membership, an owner, a verification level, or a version, and unknown fields are rejected, so a request cannot set any of them. An absent `description` or `sphere`, and one sent as null, stay unset; an absent `contacts` has every contact unset; an absent `representatives` is an empty list.
additionalProperties: false
required:
- name
properties:
name:
$ref: '#/components/schemas/OrganizationName'
description:
oneOf:
- $ref: '#/components/schemas/OrganizationDescription'
- type: 'null'
sphere:
oneOf:
- $ref: '#/components/schemas/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/components/schemas/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
items:
$ref: '#/components/schemas/OrganizationRepresentative'
OrganizationUpdate:
type: object
description: Change of the profile of an organization over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged, and a representative left out of a sent list is removed. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. The body can change the profile only. It has no field for a role, a membership, an owner, a verification level, a basis, or a card, and unknown fields are rejected, so editing the profile can neither raise a right nor raise the trust level of the organization; both change only through processes of the server.
additionalProperties: false
required:
- expected_version
properties:
expected_version:
$ref: '#/components/schemas/OrganizationVersion'
name:
$ref: '#/components/schemas/OrganizationName'
description:
oneOf:
- $ref: '#/components/schemas/OrganizationDescription'
- type: 'null'
sphere:
oneOf:
- $ref: '#/components/schemas/OrganizationSphere'
- type: 'null'
contacts:
$ref: '#/components/schemas/OrganizationContactChannels'
representatives:
type: array
maxItems: 10
items:
$ref: '#/components/schemas/OrganizationRepresentative'
OrganizationRole:
type: string
description: |-
Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.
- owner: manages the organization and its members, and acts on behalf of the company.
- recruiter: leads the selection of candidates for all needs.
- hiring_manager: acts on the needs assigned to the member.
- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.
In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.
enum:
- owner
- recruiter
- hiring_manager
- technical_expert
MembershipState:
type: string
description: |-
State of a membership. Only `active` gives access: every other state answers as if the account were no member.
- active: the member works in the organization with the role.
- suspended: access is stopped, and the owner or the platform may restore it.
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
- left: the member ended the membership.
One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.
enum:
- active
- suspended
- removed
- left
OrganizationMembership:
type: object
description: The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them.
additionalProperties: false
required:
- organization_id
- role
- state
- joined_at
properties:
organization_id:
type: string
format: uuid
description: Identifier of the organization.
role:
$ref: '#/components/schemas/OrganizationRole'
state:
$ref: '#/components/schemas/MembershipState'
joined_at:
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).
allOf:
- $ref: '#/components/schemas/Timestamp'
OrganizationSummary:
type: object
description: 'An organization in the list of the caller''s organizations: what a switcher needs to name it. The profile, the contacts, and the representatives are in `Organization`.'
additionalProperties: false
required:
- id
- name
- verification_level
properties:
id:
type: string
format: uuid
description: Identifier of the organization, the `org_id` of its paths.
name:
$ref: '#/components/schemas/OrganizationName'
verification_level:
$ref: '#/components/schemas/OrganizationVerificationLevel'
MyOrganization:
type: object
description: An organization available to the caller together with the caller's membership in it.
additionalProperties: false
required:
- organization
- membership
properties:
organization:
$ref: '#/components/schemas/OrganizationSummary'
membership:
$ref: '#/components/schemas/OrganizationMembership'
MyOrganizationList:
type: object
description: One page of the organizations available to the caller, newest membership first. It holds only organizations where the caller has an `active` membership, so it is also the list of contexts the caller can work in; it never names an organization the caller cannot enter.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Organizations of the page.
items:
$ref: '#/components/schemas/MyOrganization'
page:
$ref: '#/components/schemas/PageInfo'
HealthResponse:
type: object
additionalProperties: false
@@ -7003,6 +7581,30 @@ components:
$ref: '#/components/examples/InvitationSendBlocked'
idempotency_in_progress:
$ref: '#/components/examples/IdempotencyInProgress'
OrganizationValidationFailed:
description: 'The body does not match the contract or violates an organization rule: a missing name, an unknown field such as role, verification_level, verification, members, owner, or version, a name or sphere with surrounding whitespace or a line break, a website that is not an https URL of a host name, a phone number outside E.164, a Telegram username without the leading @, a contact that has no valid form, more than ten representatives, or a missing or invalid expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an Idempotency-Key.'
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
role_sent_by_client:
$ref: '#/components/examples/OrganizationUnknownField'
website_not_https:
$ref: '#/components/examples/OrganizationWebsiteNotHttps'
name_with_surrounding_whitespace:
$ref: '#/components/examples/OrganizationNameWithWhitespace'
missing_expected_version:
$ref: '#/components/examples/OrganizationMissingExpectedVersion'
OrganizationVersionConflict:
description: '`expected_version` is not the current version of the organization; code version_conflict. Nothing was changed; read the organization again before retrying.'
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
version_conflict:
$ref: '#/components/examples/OrganizationStaleVersion'
securitySchemes:
sessionCookie:
type: apiKey
@@ -8303,6 +8905,205 @@ components:
code: state_conflict
detail: The resource is in a state that does not allow this operation.
trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b
MyOrganizationListPage:
summary: The organizations of an owner who works in two companies
description: The caller has an active membership in both organizations, newest first. A third organization, where the caller left, is not listed.
value:
items:
- organization:
id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c
name: ИП Тестов Логистика
verification_level: e0
membership:
organization_id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c
role: owner
state: active
joined_at: '2026-10-06T11:30:00Z'
- organization:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
verification_level: e0
membership:
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
role: owner
state: active
joined_at: '2026-10-06T09:00:00Z'
page:
has_more: false
next_cursor: null
OrganizationCreateNameOnly:
summary: A company that starts with its name only
description: Only the name is required; the card is completed later with UpdateOrganization.
value:
name: ООО Пример Платежи
OrganizationCreateCompleteCard:
summary: A company that gives its whole card at creation
description: Every contact is a company channel, and the representative is presentation only. There is no field for a role or a verification level.
value:
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: '+74950000000'
telegram: '@payments_careers'
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
OrganizationNameOnly:
summary: A new organization that has only a name
description: The creator is the owner of the organization, which starts at the verification level e0 on the ground of the confirmed email. The card repeats the profile as a candidate sees it.
value:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
version: 1
name: ООО Пример Платежи
description: null
sphere: null
contacts:
website: null
email: null
phone: null
telegram: null
representatives: []
verification:
level: e0
basis: confirmed_email
changed_at: '2026-10-06T09:00:00Z'
candidate_card:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
description: null
sphere: null
contacts:
website: null
email: null
phone: null
telegram: null
representatives: []
verification_level: e0
created_at: '2026-10-06T09:00:00Z'
updated_at: '2026-10-06T09:00:00Z'
OrganizationCompleteCard:
summary: An organization with a complete card, still at the level e0
description: Completing the card, adding contacts, and listing representatives did not raise the verification level, which stays e0 and changes only through a verification process of the server.
value:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
version: 2
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: '+74950000000'
telegram: '@payments_careers'
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
verification:
level: e0
basis: confirmed_email
changed_at: '2026-10-06T09:00:00Z'
candidate_card:
id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
name: ООО Пример Платежи
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: '+74950000000'
telegram: '@payments_careers'
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
verification_level: e0
created_at: '2026-10-06T09:00:00Z'
updated_at: '2026-10-06T09:40:00Z'
OrganizationUnknownField:
summary: The client sent a role together with the profile
description: A role, an owner, a verification level, and a list of members are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body.
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5c
errors:
- in: body
pointer: ''
code: invalid
message: The value does not match the contract.
OrganizationWebsiteNotHttps:
summary: The website is not an https URL of a host name
description: A domain rule of the server, checked after the schema. The schema already refuses a value that is not an https URL; the server also refuses a port, an IP address, and a host name without a dot.
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6d
errors:
- in: body
pointer: /contacts/website
code: invalid
message: The value does not match the contract.
OrganizationNameWithWhitespace:
summary: The name has leading whitespace
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 3a4b5c6d-7e8f-4a9b-8c1d-2e3f4a5b6c7e
errors:
- in: body
pointer: /name
code: invalid
message: The value does not match the contract.
OrganizationMissingExpectedVersion:
summary: A change without expected_version
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 4b5c6d7e-8f9a-4b0c-9d2e-3f4a5b6c7d8f
errors:
- in: body
pointer: /expected_version
code: required
message: The value is required.
OrganizationUpdateCompleteCard:
summary: The owner completes the card of the organization
description: The change carries the version that the client read and the fields to replace; contacts and representatives are replaced as a whole. The body has no role or verification field.
value:
expected_version: 1
description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками.
sphere: Платежи и финансовые сервисы
contacts:
website: https://payments.example.com
email: careers@payments.example.com
phone: '+74950000000'
telegram: '@payments_careers'
representatives:
- name: Анна Тестова
job_title: Руководитель по подбору
OrganizationStaleVersion:
summary: The change carried a stale expected_version
description: Another member changed the organization after the client read it. Nothing was changed; the client reads the organization again and reapplies its edits.
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 5c6d7e8f-9a0b-4c1d-8e3f-4a5b6c7d8e90
NeedListPage:
summary: The last page of the needs of an organization
value:
+58
View File
@@ -26,6 +26,14 @@ tags:
Assessment attempts of the current candidate: availability, start and
resume, answers and the code practice, finalization, and the result.
Answers, keys, and attempt history are visible only to the candidate.
- name: organization
description: >-
Organizations of employer accounts: the profile with its contacts and
representatives, the verification level that only the server sets, and
the memberships that give an account its role in an organization. The
organization in the path is authoritative and is checked against an
active membership on every request; no body carries a role, a
membership, or a verification level.
- name: need
description: >-
Hiring needs of an organization: requirements with their confirmation
@@ -89,6 +97,12 @@ paths:
$ref: ./routes/candidate_assessment_attempt_finalize.yml
/api/v1/me/assessment-attempts/{attempt_id}/result:
$ref: ./routes/candidate_assessment_attempt_result.yml
/api/v1/me/organizations:
$ref: ./routes/my_organizations.yml
/api/v1/organizations:
$ref: ./routes/organizations.yml
/api/v1/organizations/{org_id}:
$ref: ./routes/organization.yml
/api/v1/organizations/{org_id}/needs:
$ref: ./routes/organization_needs.yml
/api/v1/organizations/{org_id}/needs/{need_id}:
@@ -599,6 +613,46 @@ components:
$ref: ./components/schemas.yml#/ConsentRecord
ConsentRecordList:
$ref: ./components/schemas.yml#/ConsentRecordList
OrganizationVersion:
$ref: ./components/schemas.yml#/OrganizationVersion
OrganizationName:
$ref: ./components/schemas.yml#/OrganizationName
OrganizationDescription:
$ref: ./components/schemas.yml#/OrganizationDescription
OrganizationSphere:
$ref: ./components/schemas.yml#/OrganizationSphere
OrganizationWebsite:
$ref: ./components/schemas.yml#/OrganizationWebsite
OrganizationContactChannels:
$ref: ./components/schemas.yml#/OrganizationContactChannels
OrganizationRepresentative:
$ref: ./components/schemas.yml#/OrganizationRepresentative
OrganizationVerificationLevel:
$ref: ./components/schemas.yml#/OrganizationVerificationLevel
OrganizationVerificationBasis:
$ref: ./components/schemas.yml#/OrganizationVerificationBasis
OrganizationVerification:
$ref: ./components/schemas.yml#/OrganizationVerification
CandidateOrganizationCard:
$ref: ./components/schemas.yml#/CandidateOrganizationCard
Organization:
$ref: ./components/schemas.yml#/Organization
OrganizationCreate:
$ref: ./components/schemas.yml#/OrganizationCreate
OrganizationUpdate:
$ref: ./components/schemas.yml#/OrganizationUpdate
OrganizationRole:
$ref: ./components/schemas.yml#/OrganizationRole
MembershipState:
$ref: ./components/schemas.yml#/MembershipState
OrganizationMembership:
$ref: ./components/schemas.yml#/OrganizationMembership
OrganizationSummary:
$ref: ./components/schemas.yml#/OrganizationSummary
MyOrganization:
$ref: ./components/schemas.yml#/MyOrganization
MyOrganizationList:
$ref: ./components/schemas.yml#/MyOrganizationList
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
@@ -704,6 +758,10 @@ components:
$ref: ./components/responses.yml#/InvitationVersionConflict
InvitationCommandConflict:
$ref: ./components/responses.yml#/InvitationCommandConflict
OrganizationValidationFailed:
$ref: ./components/responses.yml#/OrganizationValidationFailed
OrganizationVersionConflict:
$ref: ./components/responses.yml#/OrganizationVersionConflict
securitySchemes:
sessionCookie:
type: apiKey
+39
View File
@@ -0,0 +1,39 @@
get:
operationId: ListMyOrganizations
summary: List the organizations available to the current account.
description: |-
Requires the session cookie of an employer account. The account comes from the session, never from a request parameter, so the response holds only the caller's own memberships and no request can name another account.
Returns a page of the organizations in which the caller has an `active` membership, newest membership first with the organization identifier as the tie-breaker, with cursor pagination. Each item names the organization (`OrganizationSummary`) and holds the caller's role and state in it (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not list its organization, so an organization the caller cannot enter is never named, and one that the caller was removed from disappears from the list at once.
The list is the directory of the active organization context. The context is not stored on the server: every organization-scoped operation names its organization in the path `org_id`, and the server checks that identifier against the caller's active membership on every request, so a switch between organizations is a different `org_id` in the client's routes and cannot outlive a revoked membership. A client picks the context from this list, may remember the last choice in the browser as a convenience, and must read the list again after any answer 404 `not_found` from an organization path. An account with several memberships sees all of them here and works in one at a time; the rights and the data of the organizations stay separate.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden. An employer account without an organization gets an empty page, which tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 validation_failed.
security:
- sessionCookie: []
tags:
- organization
parameters:
- $ref: ../components/parameters.yml#/PageLimit
- $ref: ../components/parameters.yml#/PageCursor
responses:
"200":
description: A page of the organizations available to the current account.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/MyOrganizationList
examples:
one_organization:
$ref: ../components/examples.yml#/MyOrganizationListPage
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem
+100
View File
@@ -0,0 +1,100 @@
get:
operationId: GetOrganization
summary: Read an organization of which the caller is a member.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
- organization
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
responses:
"200":
description: The organization.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/Organization
examples:
name_only:
$ref: ../components/examples.yml#/OrganizationNameOnly
complete_card:
$ref: ../components/examples.yml#/OrganizationCompleteCard
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
patch:
operationId: UpdateOrganization
summary: Change the profile of an organization.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the organization (the FR07 matrix gives this to no other role), so a member with another role answers 403 forbidden. The role comes from the server-side membership; the body has no organization, membership, role, owner, or verification field.
Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null.
The body can change the profile only. The verification level, its basis, the card, the members, and every role are not fields of it, and unknown fields fail validation, so the owner can neither raise the trust level of the organization nor the rights of anyone by editing the profile; a longer description, a verified-looking website, or a new representative leaves the level unchanged. The level and the roles change only through processes of the server.
Versions: every committed change creates version `expected_version + 1` and answers 200 with the organization. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the organization again and reapplies its edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for needs. A body that changes nothing when applied to the current profile keeps the version and answers 200 with the current organization even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a change that already succeeded is harmless.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can answer 429 with Retry-After before any check.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- organization
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationUpdate
examples:
complete_card:
$ref: ../components/examples.yml#/OrganizationUpdateCompleteCard
responses:
"200":
description: >-
The organization after the change, or the current organization when
the body changes nothing.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/Organization
examples:
complete_card:
$ref: ../components/examples.yml#/OrganizationCompleteCard
"400":
$ref: ../components/responses.yml#/OrganizationValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"412":
$ref: ../components/responses.yml#/OrganizationVersionConflict
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
+60
View File
@@ -0,0 +1,60 @@
post:
operationId: CreateOrganization
summary: Create an organization; the caller becomes its owner.
description: |-
Requires the session cookie of an employer account with a confirmed email, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the session: the body has no owner, membership, role, verification, or version field, and unknown fields fail validation.
The server creates the organization and the owner membership of the caller (role `owner`, state `active`) in one transaction, so an organization never exists without its owner. The organization starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be requested: the creator of a company with a corporate domain, a long description, or many representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of the server that do not exist yet. Only `name` is required; the rest of the card can be completed with UpdateOrganization.
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second organization. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. Two requests with different keys are two organizations; the product may limit the number of organizations per account (open question), which would answer 409 `state_conflict` without a change of the schema.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- organization
parameters:
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationCreate
examples:
name_only:
$ref: ../components/examples.yml#/OrganizationCreateNameOnly
complete_card:
$ref: ../components/examples.yml#/OrganizationCreateCompleteCard
responses:
"201":
description: >-
The organization was created with the caller as its owner, or a retry
with the same Idempotency-Key replayed its creation.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/Organization
examples:
name_only:
$ref: ../components/examples.yml#/OrganizationNameOnly
complete_card:
$ref: ../components/examples.yml#/OrganizationCompleteCard
"400":
$ref: ../components/responses.yml#/OrganizationValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"409":
$ref: ../components/responses.yml#/IdempotencyInProgress
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem