feat(org): add organization and membership contract and storage
This commit is contained in:
1 parent
a0551a34b8
commit
bdc5855001
90 files changed
+17545
-480
No files matched your search
+66
-1
@@ -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
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,227 @@
|
||||
-- +goose Up
|
||||
-- Organizations, their public representatives, and the memberships that give
|
||||
-- an account a role in an organization (PRD 2.2, FR07, and 6.4). Enum-like
|
||||
-- columns are text with CHECK constraints, as in the identity tables.
|
||||
--
|
||||
-- The organization row holds the profile that the owner edits and the
|
||||
-- verification level that only the server sets. The columns of the two are
|
||||
-- separate on purpose: the profile update statement never names the
|
||||
-- verification columns, so editing a profile cannot move the level. Every
|
||||
-- time comes from the application clock.
|
||||
--
|
||||
-- The rows hold personal data of employees (representative names, the
|
||||
-- membership of an account), so the application never copies them into
|
||||
-- logs, metrics, or events beyond identifiers.
|
||||
CREATE TABLE organizations (
|
||||
-- UUIDv7 generated in Go. It is the org_id of every organization path.
|
||||
id uuid NOT NULL,
|
||||
-- The name consent records snapshot, so the bound equals the bound of
|
||||
-- consent_records.organization_name.
|
||||
name text NOT NULL,
|
||||
description text,
|
||||
-- Field of business as free text; the product has no sphere taxonomy.
|
||||
sphere text,
|
||||
-- Public company contacts only, never personal ones. Each is NULL or a
|
||||
-- value in the format of the contract; the domain checks them in full.
|
||||
contact_website text,
|
||||
contact_email text,
|
||||
contact_phone text,
|
||||
contact_telegram text,
|
||||
-- Trust level (PRD FR07). It starts at e0 and moves only by a
|
||||
-- verification process of the server, which will record the change in
|
||||
-- its own history table. No profile statement writes these columns.
|
||||
verification_level text NOT NULL,
|
||||
verification_basis text NOT NULL,
|
||||
verification_changed_at timestamptz NOT NULL,
|
||||
-- Optimistic concurrency version of the profile, advanced by every
|
||||
-- profile update.
|
||||
version bigint NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT organizations_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT organizations_name_format CHECK (
|
||||
char_length(name) BETWEEN 1 AND 200
|
||||
AND name !~ '^\s|\s$'
|
||||
AND name !~ '[[:cntrl:]]'
|
||||
),
|
||||
-- Line breaks are allowed inside the text; every other control
|
||||
-- character, and whitespace at the ends, are not.
|
||||
CONSTRAINT organizations_description_format CHECK (
|
||||
description IS NULL OR (
|
||||
char_length(description) BETWEEN 1 AND 2000
|
||||
AND description !~ '^\s|\s$'
|
||||
AND translate(description, E'\n', '') !~ '[[:cntrl:]]'
|
||||
)
|
||||
),
|
||||
CONSTRAINT organizations_sphere_format CHECK (
|
||||
sphere IS NULL OR (
|
||||
char_length(sphere) BETWEEN 1 AND 100
|
||||
AND sphere !~ '^\s|\s$'
|
||||
AND sphere !~ '[[:cntrl:]]'
|
||||
)
|
||||
),
|
||||
CONSTRAINT organizations_contact_website_format CHECK (
|
||||
contact_website IS NULL OR (
|
||||
char_length(contact_website) BETWEEN 9 AND 300
|
||||
AND contact_website ~ '^https://[^\s/?#@]+([/?#]\S*)?$'
|
||||
)
|
||||
),
|
||||
CONSTRAINT organizations_contact_email_format CHECK (
|
||||
contact_email IS NULL OR (
|
||||
char_length(contact_email) BETWEEN 3 AND 254
|
||||
AND contact_email ~ '^[^@\s]+@[^@\s]+$'
|
||||
)
|
||||
),
|
||||
CONSTRAINT organizations_contact_phone_format CHECK (
|
||||
contact_phone IS NULL OR contact_phone ~ '^\+[1-9][0-9]{6,14}$'
|
||||
),
|
||||
CONSTRAINT organizations_contact_telegram_format CHECK (
|
||||
contact_telegram IS NULL OR contact_telegram ~ '^@[A-Za-z0-9_]{5,32}$'
|
||||
),
|
||||
-- Each level has its own bases (PRD FR07), so a level never carries the
|
||||
-- ground of another one.
|
||||
CONSTRAINT organizations_verification_known CHECK (
|
||||
(verification_level = 'e0' AND verification_basis = 'confirmed_email')
|
||||
OR (
|
||||
verification_level = 'e1'
|
||||
AND verification_basis = 'corporate_domain'
|
||||
)
|
||||
OR (
|
||||
verification_level = 'e2'
|
||||
AND verification_basis = 'requisites_and_authority'
|
||||
)
|
||||
OR (
|
||||
verification_level = 'e3'
|
||||
AND verification_basis IN ('manual_review', 'partner_status')
|
||||
)
|
||||
),
|
||||
CONSTRAINT organizations_version_positive CHECK (version > 0),
|
||||
CONSTRAINT organizations_timestamps_after_creation CHECK (
|
||||
updated_at >= created_at
|
||||
AND verification_changed_at >= created_at
|
||||
)
|
||||
);
|
||||
|
||||
-- The representatives that the owner presents on the card. They are
|
||||
-- presentation only: no account link, no right. The list is replaced as a
|
||||
-- whole with the organization update, in the order of ordinal.
|
||||
CREATE TABLE organization_representatives (
|
||||
organization_id uuid NOT NULL,
|
||||
-- Position in the list, from 0; at most ten representatives.
|
||||
ordinal smallint NOT NULL,
|
||||
name text NOT NULL,
|
||||
job_title text NOT NULL,
|
||||
CONSTRAINT organization_representatives_pkey PRIMARY KEY (
|
||||
organization_id, ordinal
|
||||
),
|
||||
-- The list is part of the organization row and goes with it.
|
||||
CONSTRAINT organization_representatives_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE CASCADE,
|
||||
CONSTRAINT organization_representatives_ordinal_range CHECK (
|
||||
ordinal BETWEEN 0 AND 9
|
||||
),
|
||||
CONSTRAINT organization_representatives_name_format CHECK (
|
||||
char_length(name) BETWEEN 1 AND 100
|
||||
AND name !~ '^\s|\s$'
|
||||
AND name !~ '[[:cntrl:]]'
|
||||
),
|
||||
CONSTRAINT organization_representatives_job_title_format CHECK (
|
||||
char_length(job_title) BETWEEN 1 AND 100
|
||||
AND job_title !~ '^\s|\s$'
|
||||
AND job_title !~ '[[:cntrl:]]'
|
||||
)
|
||||
);
|
||||
|
||||
-- One row per account and organization, whatever its role and state: a
|
||||
-- former member who returns gets the same row back in the active state, and
|
||||
-- the history of the pair belongs to the audit events. The role lives only
|
||||
-- here, never on the organization. Only an active membership gives access;
|
||||
-- the full role matrix (PRD FR07) is applied by the application, and a row
|
||||
-- grants nothing by itself.
|
||||
CREATE TABLE memberships (
|
||||
-- UUIDv7 generated in Go; the planned assignments of needs refer to it.
|
||||
id uuid NOT NULL,
|
||||
organization_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
-- owner, recruiter, hiring_manager, or technical_expert.
|
||||
role text NOT NULL,
|
||||
-- active, suspended, removed (by the owner or the platform), or left (by
|
||||
-- the member).
|
||||
state text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT memberships_pkey PRIMARY KEY (id),
|
||||
-- A repeated membership of the same pair fails here. The leading
|
||||
-- user_id also serves the list of an account's organizations.
|
||||
CONSTRAINT memberships_user_id_organization_id_key UNIQUE (
|
||||
user_id, organization_id
|
||||
),
|
||||
-- Target of the composite foreign keys that later tables use to bind a
|
||||
-- membership to its organization, such as the assignments of needs.
|
||||
CONSTRAINT memberships_organization_id_id_key UNIQUE (
|
||||
organization_id, id
|
||||
),
|
||||
-- Both references restrict: an organization with members and an account
|
||||
-- with memberships cannot be deleted until an explicit procedure ends
|
||||
-- the memberships first. The application never deletes an organization.
|
||||
CONSTRAINT memberships_organization_id_fkey FOREIGN KEY (
|
||||
organization_id
|
||||
) REFERENCES organizations (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT memberships_user_id_fkey FOREIGN KEY (
|
||||
user_id
|
||||
) REFERENCES users (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT memberships_role_known CHECK (
|
||||
role IN ('owner', 'recruiter', 'hiring_manager', 'technical_expert')
|
||||
),
|
||||
CONSTRAINT memberships_state_known CHECK (
|
||||
state IN ('active', 'suspended', 'removed', 'left')
|
||||
),
|
||||
CONSTRAINT memberships_updated_after_creation CHECK (
|
||||
updated_at >= created_at
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the members of an organization and the foreign key.
|
||||
CREATE INDEX memberships_organization_id_idx
|
||||
ON memberships (organization_id);
|
||||
|
||||
-- Refuses an organization that has no active owner when the transaction that
|
||||
-- inserted it commits (SQLSTATE 23514, constraint
|
||||
-- organizations_owner_required). The check is deferred, so the organization
|
||||
-- and its owner membership are inserted in either order inside one
|
||||
-- transaction, and a transaction that fails between the two statements
|
||||
-- leaves neither. Removing or demoting the last owner later is a rule of
|
||||
-- the member management, not of this constraint.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION organizations_require_owner() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM memberships
|
||||
WHERE
|
||||
memberships.organization_id = NEW.id
|
||||
AND memberships.role = 'owner'
|
||||
AND memberships.state = 'active'
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'organizations_owner_required',
|
||||
TABLE = 'organizations',
|
||||
MESSAGE = 'an organization needs an active owner';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE CONSTRAINT TRIGGER organizations_owner_required
|
||||
AFTER INSERT ON organizations
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION organizations_require_owner();
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE memberships;
|
||||
DROP TABLE organization_representatives;
|
||||
DROP TABLE organizations;
|
||||
DROP FUNCTION organizations_require_owner();
|
||||
@@ -0,0 +1,224 @@
|
||||
-- Stores a new organization with the verification level that the domain
|
||||
-- gave it. The deferred constraint organizations_owner_required fails the
|
||||
-- transaction at commit unless an active owner membership was inserted in
|
||||
-- it too.
|
||||
-- name: InsertOrganization :exec
|
||||
INSERT INTO organizations (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
sphere,
|
||||
contact_website,
|
||||
contact_email,
|
||||
contact_phone,
|
||||
contact_telegram,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(name),
|
||||
sqlc.narg(description),
|
||||
sqlc.narg(sphere),
|
||||
sqlc.narg(contact_website),
|
||||
sqlc.narg(contact_email),
|
||||
sqlc.narg(contact_phone),
|
||||
sqlc.narg(contact_telegram),
|
||||
sqlc.arg(verification_level),
|
||||
sqlc.arg(verification_basis),
|
||||
sqlc.arg(verification_changed_at),
|
||||
sqlc.arg(version),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at)
|
||||
);
|
||||
|
||||
-- Stores one representative at its position in the list. The adapter calls it
|
||||
-- once per representative after it deleted the previous list, in the same
|
||||
-- transaction.
|
||||
-- name: InsertOrganizationRepresentative :exec
|
||||
INSERT INTO organization_representatives (
|
||||
organization_id,
|
||||
ordinal,
|
||||
name,
|
||||
job_title
|
||||
) VALUES (
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(name),
|
||||
sqlc.arg(job_title)
|
||||
);
|
||||
|
||||
-- name: DeleteOrganizationRepresentatives :exec
|
||||
DELETE FROM organization_representatives
|
||||
WHERE organization_id = sqlc.arg(organization_id);
|
||||
|
||||
-- Reads an organization together with the membership of one account in it
|
||||
-- and its representatives in list order, as one statement, so the profile and
|
||||
-- the list come from one snapshot. Only an active membership matches, so an
|
||||
-- unknown organization, an account that is no member, and a suspended,
|
||||
-- removed, or left member all return no row and cannot be told apart.
|
||||
-- name: GetOrganizationForMember :one
|
||||
SELECT
|
||||
organization.id,
|
||||
organization.name,
|
||||
organization.description,
|
||||
organization.sphere,
|
||||
organization.contact_website,
|
||||
organization.contact_email,
|
||||
organization.contact_phone,
|
||||
organization.contact_telegram,
|
||||
organization.verification_level,
|
||||
organization.verification_basis,
|
||||
organization.verification_changed_at,
|
||||
organization.version,
|
||||
organization.created_at,
|
||||
organization.updated_at,
|
||||
coalesce((
|
||||
SELECT
|
||||
jsonb_agg(
|
||||
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
|
||||
ORDER BY representative.ordinal
|
||||
)
|
||||
FROM organization_representatives AS representative
|
||||
WHERE representative.organization_id = organization.id
|
||||
), '[]'::jsonb)::text AS representatives,
|
||||
membership.id AS membership_id,
|
||||
membership.role AS membership_role,
|
||||
membership.state AS membership_state,
|
||||
membership.created_at AS membership_created_at,
|
||||
membership.updated_at AS membership_updated_at
|
||||
FROM organizations AS organization
|
||||
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
|
||||
WHERE
|
||||
organization.id = sqlc.arg(organization_id)
|
||||
AND membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active';
|
||||
|
||||
-- Changes the profile of an organization over the version the caller read
|
||||
-- and advances the version in the same statement. It names no verification
|
||||
-- column, so a profile update cannot move the trust level. The change
|
||||
-- applies only for an account whose active membership has one of the
|
||||
-- manager roles, checked in the statement itself so that a membership that
|
||||
-- ended after the caller's read still stops the write. The statement locks
|
||||
-- the organization row first and then the actor's membership row FOR SHARE,
|
||||
-- so a revocation that commits while the statement waits is seen again
|
||||
-- (EvalPlanQual) and stops the write; the order organizations, then
|
||||
-- memberships, is the lock order of every writer (member management must
|
||||
-- follow it). No row returns for a stale version, an account that is no
|
||||
-- active manager, or an unknown organization; the adapter reads the
|
||||
-- membership to tell them apart.
|
||||
-- name: UpdateOrganizationProfile :one
|
||||
WITH target AS (
|
||||
SELECT id FROM organizations
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
FOR UPDATE
|
||||
),
|
||||
|
||||
actor AS (
|
||||
SELECT memberships.id FROM memberships
|
||||
INNER JOIN target ON memberships.organization_id = target.id
|
||||
WHERE
|
||||
memberships.user_id = sqlc.arg(actor_id)
|
||||
AND memberships.state = 'active'
|
||||
AND memberships.role = any(sqlc.arg(manager_roles)::text [])
|
||||
FOR SHARE OF memberships
|
||||
)
|
||||
|
||||
UPDATE organizations
|
||||
SET
|
||||
name = sqlc.arg(name),
|
||||
description = sqlc.narg(description),
|
||||
sphere = sqlc.narg(sphere),
|
||||
contact_website = sqlc.narg(contact_website),
|
||||
contact_email = sqlc.narg(contact_email),
|
||||
contact_phone = sqlc.narg(contact_phone),
|
||||
contact_telegram = sqlc.narg(contact_telegram),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
version = organizations.version + 1
|
||||
FROM actor
|
||||
WHERE
|
||||
organizations.id = sqlc.arg(id)
|
||||
AND organizations.version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
organizations.id,
|
||||
organizations.name,
|
||||
organizations.description,
|
||||
organizations.sphere,
|
||||
organizations.contact_website,
|
||||
organizations.contact_email,
|
||||
organizations.contact_phone,
|
||||
organizations.contact_telegram,
|
||||
organizations.verification_level,
|
||||
organizations.verification_basis,
|
||||
organizations.verification_changed_at,
|
||||
organizations.version,
|
||||
organizations.created_at,
|
||||
organizations.updated_at;
|
||||
|
||||
-- Lists the organizations where an account has an active membership,
|
||||
-- newest membership first. The page continues after the (membership
|
||||
-- creation time, organization ID) position of the last item of the
|
||||
-- previous page. Only the active memberships of the given account match.
|
||||
-- name: ListOrganizationsForUser :many
|
||||
SELECT
|
||||
organization.id,
|
||||
organization.name,
|
||||
organization.verification_level,
|
||||
membership.id AS membership_id,
|
||||
membership.role AS membership_role,
|
||||
membership.state AS membership_state,
|
||||
membership.created_at AS membership_created_at,
|
||||
membership.updated_at AS membership_updated_at
|
||||
FROM memberships AS membership
|
||||
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
|
||||
WHERE
|
||||
membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active'
|
||||
AND (
|
||||
sqlc.narg(after_joined_at)::timestamptz IS NULL
|
||||
OR (membership.created_at, membership.organization_id) < (
|
||||
sqlc.narg(after_joined_at)::timestamptz,
|
||||
sqlc.narg(after_organization_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY membership.created_at DESC, membership.organization_id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: InsertMembership :exec
|
||||
INSERT INTO memberships (
|
||||
id,
|
||||
organization_id,
|
||||
user_id,
|
||||
role,
|
||||
state,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(role),
|
||||
sqlc.arg(state),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at)
|
||||
);
|
||||
|
||||
-- Reads the membership of one account in one organization, in any state.
|
||||
-- name: GetMembership :one
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
user_id,
|
||||
role,
|
||||
state,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM memberships
|
||||
WHERE
|
||||
organization_id = sqlc.arg(organization_id)
|
||||
AND user_id = sqlc.arg(user_id);
|
||||
@@ -89,7 +89,7 @@ func TestConsentLedger(t *testing.T) {
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
// Every table that references users must be truncated with it.
|
||||
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
}
|
||||
|
||||
t.Run("migration publishes one demo text per purpose bound to its hash", func(t *testing.T) {
|
||||
|
||||
@@ -5,7 +5,6 @@ package integration_test
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -155,7 +154,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
fixture.nowNanos.Store(start.UnixNano())
|
||||
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
}
|
||||
|
||||
t.Run("C1 is written in the registration transaction and the other purposes separately", func(t *testing.T) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -134,7 +135,7 @@ func TestMailDelivery(t *testing.T) {
|
||||
{"consumer_processed_events"},
|
||||
{"consumer_dead_letters"},
|
||||
}, deliveryTables...)
|
||||
truncateTables(ctx, t, pool, append(append(tables, identityTables...), consentTables...)...)
|
||||
truncateTables(ctx, t, pool, slices.Concat(tables, usersDependentTables)...)
|
||||
}
|
||||
|
||||
t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -72,7 +71,7 @@ func TestIdentityRepositories(t *testing.T) {
|
||||
t.Helper()
|
||||
// The deliveries and consent records reference users, so TRUNCATE
|
||||
// must name them too.
|
||||
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
}
|
||||
|
||||
t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -62,7 +63,7 @@ func TestMailQuota(t *testing.T) {
|
||||
harness.recipients = &deliveryHarness{env: env, pool: pool, identity: postgresadapter.NewIdentityStore(pool), logs: harness.logs}
|
||||
reset := func(t *testing.T, now time.Time) domain.User {
|
||||
t.Helper()
|
||||
truncateTables(ctx, t, pool, append([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, append(append(deliveryTables, identityTables...), consentTables...)...)...)
|
||||
truncateTables(ctx, t, pool, slices.Concat([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, usersDependentTables)...)
|
||||
harness.now = now
|
||||
harness.recipients.now = now
|
||||
return harness.recipients.createRecipient(ctx, t, true)
|
||||
|
||||
@@ -0,0 +1,979 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
organizationTestTimeout = 3 * time.Minute
|
||||
// concurrentOrganizationUpdates change one organization at once from the
|
||||
// same version, each on its own connection.
|
||||
concurrentOrganizationUpdates = 8
|
||||
organizationUniqueViolation = "23505"
|
||||
organizationCheckViolation = "23514"
|
||||
organizationRestrictViolation = "23001"
|
||||
)
|
||||
|
||||
var (
|
||||
organizationsTable = pgx.Identifier{"organizations"}
|
||||
organizationRepresentativesTable = pgx.Identifier{"organization_representatives"}
|
||||
membershipsTable = pgx.Identifier{"memberships"}
|
||||
// organizationTables are emptied together: memberships reference both
|
||||
// users and organizations.
|
||||
organizationTables = []pgx.Identifier{membershipsTable, organizationRepresentativesTable, organizationsTable}
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
// truncated between subtests.
|
||||
type organizationFixture struct {
|
||||
ctx context.Context
|
||||
pool *pgxpool.Pool
|
||||
identity identityFixture
|
||||
transactor *postgresadapter.Transactor
|
||||
// now is truncated to microseconds, the precision PostgreSQL stores.
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestOrganizationsAndMemberships(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
fixture := organizationFixture{
|
||||
ctx: ctx,
|
||||
pool: pool,
|
||||
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
|
||||
transactor: postgresadapter.NewTransactor(pool),
|
||||
now: now,
|
||||
}
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
}
|
||||
|
||||
t.Run("stores an organization with its owner and reads it back for the member", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример Платежи"), now)
|
||||
|
||||
read, membership, err := fixture.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("GetForMember() error = %v", err)
|
||||
}
|
||||
if !read.Profile().Equal(organization.Profile()) || read.Version() != 1 || !read.CreatedAt().Equal(now) || !read.UpdatedAt().Equal(now) {
|
||||
t.Fatalf("stored organization = %v, want the created profile at version 1", read)
|
||||
}
|
||||
if verification := read.Verification(); verification.Level() != domain.OrganizationVerificationE0 ||
|
||||
verification.Basis() != domain.OrganizationBasisConfirmedEmail || !verification.ChangedAt().Equal(now) {
|
||||
t.Fatalf("verification = %s %s, want e0 on the confirmed email", verification.Level(), verification.Basis())
|
||||
}
|
||||
if membership.Role() != domain.OrganizationRoleOwner || membership.State() != domain.MembershipStateActive ||
|
||||
membership.UserID() != owner.ID || membership.OrganizationID() != organization.ID() {
|
||||
t.Fatalf("membership = %+v, want the active owner membership of the creator", membership)
|
||||
}
|
||||
if got := read.Profile().Representatives(); len(got) != 2 || got[0].Name() != "Анна Тестова" || got[1].Name() != "Борис Образцов" {
|
||||
t.Fatalf("representatives = %v, want two in the given order", got)
|
||||
}
|
||||
|
||||
// The stored values are NULL for a field that is not set, not an
|
||||
// empty string.
|
||||
minimal := fixture.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Только имя"}), now.Add(time.Minute))
|
||||
var description, website *string
|
||||
if err := pool.QueryRow(ctx, `SELECT description, contact_website FROM organizations WHERE id = $1`, minimal.ID()).Scan(&description, &website); err != nil {
|
||||
t.Fatalf("select the minimal organization: %v", err)
|
||||
}
|
||||
if description != nil || website != nil {
|
||||
t.Fatalf("description = %v, website = %v, want NULL for fields that are not set", description, website)
|
||||
}
|
||||
bare, _, err := fixture.read(owner.ID, minimal.ID())
|
||||
if err != nil || len(bare.Profile().Representatives()) != 0 {
|
||||
t.Fatalf("GetForMember(organization without representatives) = %v, %v, want an empty list", bare, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a repeated membership of the same pair violates the unique constraint in any state", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
|
||||
for _, role := range domain.OrganizationRoles() {
|
||||
repeated, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: owner.ID, Role: role, At: now.Add(time.Hour)})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership(%s) error = %v", role, err)
|
||||
}
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Memberships().Insert(ctx, repeated)
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrMembershipExists) || !strings.Contains(err.Error(), "memberships_user_id_organization_id_key") {
|
||||
t.Fatalf("Insert(repeated %s) error = %v, want ErrMembershipExists naming the constraint", role, err)
|
||||
}
|
||||
}
|
||||
// A membership that ended keeps its row, so the pair stays taken.
|
||||
fixture.setMembershipState(t, organization.ID(), owner.ID, domain.MembershipStateLeft)
|
||||
repeated, err := domain.NewOwnerMembership(organization.ID(), owner.ID, now.Add(time.Hour))
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Memberships().Insert(ctx, repeated)
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrMembershipExists) {
|
||||
t.Fatalf("Insert(after the member left) error = %v, want ErrMembershipExists", err)
|
||||
}
|
||||
// The database refuses it without the adapter, too.
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, 'recruiter', 'active', $4, $4)`, uuid.New(), organization.ID(), owner.ID, now)
|
||||
assertSQLError(t, "raw duplicate membership", err, organizationUniqueViolation, "memberships_user_id_organization_id_key")
|
||||
assertRowCount(ctx, t, pool, membershipsTable, 1)
|
||||
|
||||
// Another account, or another organization, is another pair.
|
||||
second := fixture.employer(t, "second@example.com")
|
||||
fixture.addMember(t, organization, second, domain.OrganizationRoleRecruiter, now.Add(2*time.Hour))
|
||||
other := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другое"), now.Add(3*time.Hour))
|
||||
if _, _, err := fixture.read(owner.ID, other.ID()); err != nil {
|
||||
t.Fatalf("GetForMember(second organization of the same account) error = %v", err)
|
||||
}
|
||||
assertRowCount(ctx, t, pool, membershipsTable, 3)
|
||||
|
||||
if _, err := fixture.getMembership(organization.ID(), second.ID); err != nil {
|
||||
t.Fatalf("Get(membership) error = %v", err)
|
||||
}
|
||||
if _, err := fixture.getMembership(organization.ID(), uuid.New()); !errors.Is(err, outbound.ErrMembershipNotFound) {
|
||||
t.Fatalf("Get(unknown account) error = %v, want ErrMembershipNotFound", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an organization and its owner are stored atomically", func(t *testing.T) {
|
||||
reset(t)
|
||||
creator := fixture.employer(t, "creator@example.com")
|
||||
|
||||
// The owner row fails on a foreign key: the organization, its
|
||||
// representatives, and the membership are all rolled back.
|
||||
organization := fixture.newOrganization(t, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
unknownOwner, err := domain.NewOwnerMembership(organization.ID(), uuid.New(), now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Organizations().CreateWithOwner(ctx, organization, unknownOwner)
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrUserNotFound) {
|
||||
t.Fatalf("CreateWithOwner(unknown account) error = %v, want ErrUserNotFound", err)
|
||||
}
|
||||
fixture.assertNothingStored(t)
|
||||
|
||||
// A later failure of the same transaction removes the organization.
|
||||
owner, err := domain.NewOwnerMembership(organization.ID(), creator.ID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
failure := errors.New("the usecase failed after the organization was stored")
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := unit.Organizations().CreateWithOwner(ctx, organization, owner); err != nil {
|
||||
return err
|
||||
}
|
||||
return failure
|
||||
})
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("transaction error = %v, want the usecase failure", err)
|
||||
}
|
||||
fixture.assertNothingStored(t)
|
||||
|
||||
// The adapter refuses an owner that is not the active owner of the
|
||||
// organization before it writes anything.
|
||||
recruiter, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: creator.ID, Role: domain.OrganizationRoleRecruiter, At: now})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
foreign, err := domain.NewOwnerMembership(uuid.New(), creator.ID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
for name, membership := range map[string]domain.Membership{"recruiter": recruiter, "owner of another organization": foreign, "zero": {}} {
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Organizations().CreateWithOwner(ctx, organization, membership)
|
||||
})
|
||||
if !errors.Is(err, domain.ErrInvalidMembership) {
|
||||
t.Fatalf("CreateWithOwner(%s) error = %v, want ErrInvalidMembership", name, err)
|
||||
}
|
||||
}
|
||||
fixture.assertNothingStored(t)
|
||||
|
||||
// Success stores all three.
|
||||
fixture.create(t, creator, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
assertRowCount(ctx, t, pool, organizationsTable, 1)
|
||||
assertRowCount(ctx, t, pool, organizationRepresentativesTable, 2)
|
||||
assertRowCount(ctx, t, pool, membershipsTable, 1)
|
||||
})
|
||||
|
||||
t.Run("the database refuses to commit an organization without an active owner", func(t *testing.T) {
|
||||
reset(t)
|
||||
member := fixture.employer(t, "member@example.com")
|
||||
insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO organizations (
|
||||
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
|
||||
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2)`, id, now)
|
||||
return err
|
||||
}
|
||||
insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error {
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organizationID, member.ID, role, state, now)
|
||||
return err
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
work func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error
|
||||
}{
|
||||
{"no membership at all", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { return insertOrganization(ctx, tx, id) }},
|
||||
{"only a recruiter", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
|
||||
if err := insertOrganization(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return insertMember(ctx, tx, id, "recruiter", "active")
|
||||
}},
|
||||
{"an owner that is removed in the same transaction", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
|
||||
if err := insertOrganization(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertMember(ctx, tx, id, "owner", "active"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1`, id)
|
||||
return err
|
||||
}},
|
||||
{"only a suspended owner", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
|
||||
if err := insertOrganization(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return insertMember(ctx, tx, id, "owner", "suspended")
|
||||
}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
|
||||
if !ok {
|
||||
t.Fatal("the unit of work has no PostgreSQL transaction")
|
||||
}
|
||||
return test.work(ctx, tx, uuid.New())
|
||||
})
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) || pgError.Code != organizationCheckViolation || pgError.ConstraintName != "organizations_owner_required" {
|
||||
t.Fatalf("commit error = %v, want SQLSTATE %s on organizations_owner_required", err, organizationCheckViolation)
|
||||
}
|
||||
fixture.assertNothingStored(t)
|
||||
})
|
||||
}
|
||||
|
||||
// An active owner inserted after the organization, in the same
|
||||
// transaction, satisfies the deferred check.
|
||||
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
tx, _ := postgresadapter.TransactionForIntegrationTest(unit)
|
||||
id := uuid.New()
|
||||
if err := insertOrganization(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return insertMember(ctx, tx, id, "owner", "active")
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("organization with an owner in one transaction error = %v", err)
|
||||
}
|
||||
assertRowCount(ctx, t, pool, organizationsTable, 1)
|
||||
})
|
||||
|
||||
t.Run("lists only the active organizations of the caller", func(t *testing.T) {
|
||||
reset(t)
|
||||
alice := fixture.employer(t, "alice@example.com")
|
||||
bob := fixture.employer(t, "bob@example.com")
|
||||
carol := fixture.employer(t, "carol@example.com")
|
||||
at := func(minutes int) time.Time { return now.Add(time.Duration(minutes) * time.Minute) }
|
||||
first := fixture.create(t, alice, fixture.completeProfile(t, "Первая Алисы"), at(1))
|
||||
bobs := fixture.create(t, bob, fixture.completeProfile(t, "Бобова"), at(2))
|
||||
third := fixture.create(t, alice, fixture.completeProfile(t, "Третья Алисы"), at(3))
|
||||
shared := fixture.create(t, bob, fixture.completeProfile(t, "Общая"), at(4))
|
||||
fixture.addMember(t, shared, alice, domain.OrganizationRoleRecruiter, at(5))
|
||||
suspended := fixture.create(t, bob, fixture.completeProfile(t, "Приостановленная"), at(6))
|
||||
fixture.addMember(t, suspended, alice, domain.OrganizationRoleHiringManager, at(7))
|
||||
fixture.setMembershipState(t, suspended.ID(), alice.ID, domain.MembershipStateSuspended)
|
||||
left := fixture.create(t, bob, fixture.completeProfile(t, "Покинутая"), at(8))
|
||||
fixture.addMember(t, left, alice, domain.OrganizationRoleTechnicalExpert, at(9))
|
||||
fixture.setMembershipState(t, left.ID(), alice.ID, domain.MembershipStateLeft)
|
||||
removed := fixture.create(t, bob, fixture.completeProfile(t, "Удаленная"), at(10))
|
||||
fixture.addMember(t, removed, alice, domain.OrganizationRoleRecruiter, at(11))
|
||||
fixture.setMembershipState(t, removed.ID(), alice.ID, domain.MembershipStateRemoved)
|
||||
|
||||
page := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 10})
|
||||
wantOrder := []uuid.UUID{shared.ID(), third.ID(), first.ID()}
|
||||
if got := organizationIDs(page); !slices.Equal(got, wantOrder) || page.HasMore {
|
||||
t.Fatalf("Alice's organizations = %v (more %v), want %v newest membership first", got, page.HasMore, wantOrder)
|
||||
}
|
||||
if page.Items[0].Membership.Role() != domain.OrganizationRoleRecruiter || page.Items[1].Membership.Role() != domain.OrganizationRoleOwner ||
|
||||
page.Items[0].Organization.Name() != "Общая" || page.Items[0].Organization.VerificationLevel() != domain.OrganizationVerificationE0 ||
|
||||
page.Items[0].Membership.UserID() != alice.ID {
|
||||
t.Fatalf("items = %+v, want each organization with Alice's own membership", page.Items)
|
||||
}
|
||||
|
||||
bobPage := fixture.list(t, outbound.OrganizationListQuery{UserID: bob.ID, Limit: 10})
|
||||
if got := organizationIDs(bobPage); len(got) != 5 || slices.Contains(got, first.ID()) || slices.Contains(got, third.ID()) || !slices.Contains(got, bobs.ID()) {
|
||||
t.Fatalf("Bob's organizations = %v, want his five and none of Alice's own", got)
|
||||
}
|
||||
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); len(got) != 0 {
|
||||
t.Fatalf("Carol's organizations = %v, want none", got)
|
||||
}
|
||||
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: uuid.New(), Limit: 10})); len(got) != 0 {
|
||||
t.Fatalf("an unknown account's organizations = %v, want none", got)
|
||||
}
|
||||
|
||||
// Paging follows the same order without a gap or a repeat.
|
||||
firstPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2})
|
||||
if !firstPage.HasMore || len(firstPage.Items) != 2 {
|
||||
t.Fatalf("first page = %d items (more %v), want 2 and more", len(firstPage.Items), firstPage.HasMore)
|
||||
}
|
||||
last := outbound.OrganizationPositionOf(firstPage.Items[1])
|
||||
secondPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2, After: &last})
|
||||
if got := append(organizationIDs(firstPage), organizationIDs(secondPage)...); !slices.Equal(got, wantOrder) || secondPage.HasMore {
|
||||
t.Fatalf("pages = %v (more %v), want %v and the end", got, secondPage.HasMore, wantOrder)
|
||||
}
|
||||
|
||||
// Memberships created at the same instant order by the organization.
|
||||
tie := fixture.create(t, carol, fixture.completeProfile(t, "Ничья А"), at(20))
|
||||
tieB := fixture.create(t, carol, fixture.completeProfile(t, "Ничья Б"), at(20))
|
||||
wantTie := []uuid.UUID{tie.ID(), tieB.ID()}
|
||||
slices.SortFunc(wantTie, func(left, right uuid.UUID) int { return strings.Compare(right.String(), left.String()) })
|
||||
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); !slices.Equal(got, wantTie) {
|
||||
t.Fatalf("tied memberships = %v, want %v by organization ID descending", got, wantTie)
|
||||
}
|
||||
|
||||
for name, query := range map[string]outbound.OrganizationListQuery{
|
||||
"nil user": {Limit: 10},
|
||||
"zero limit": {UserID: alice.ID},
|
||||
"limit too large": {UserID: alice.ID, Limit: outbound.MaxOrganizationPageSize + 1},
|
||||
"zero position": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{}},
|
||||
"position without an organization": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{JoinedAt: now}},
|
||||
} {
|
||||
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := unit.Organizations().ListForUser(ctx, query)
|
||||
return err
|
||||
})
|
||||
if !errors.Is(err, domain.ErrInvalidMembership) {
|
||||
t.Fatalf("ListForUser(%s) error = %v, want ErrInvalidMembership", name, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("only an active member reads an organization, and a revoked membership closes the next read", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
outsider := fixture.employer(t, "outsider@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
stored := fixture.employer(t, "former@example.com")
|
||||
fixture.addMember(t, organization, stored, domain.OrganizationRoleRecruiter, now.Add(time.Minute))
|
||||
|
||||
for name, userID := range map[string]uuid.UUID{"an account that is no member": outsider.ID, "an unknown account": uuid.New()} {
|
||||
if _, _, err := fixture.read(userID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("GetForMember(%s) error = %v, want ErrOrganizationNotFound", name, err)
|
||||
}
|
||||
}
|
||||
if _, _, err := fixture.read(owner.ID, uuid.New()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("GetForMember(unknown organization) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
|
||||
if _, membership, err := fixture.read(stored.ID, organization.ID()); err != nil || membership.Role() != domain.OrganizationRoleRecruiter {
|
||||
t.Fatalf("GetForMember(recruiter) = %+v, %v, want the recruiter membership", membership, err)
|
||||
}
|
||||
for _, state := range []domain.MembershipState{domain.MembershipStateSuspended, domain.MembershipStateRemoved, domain.MembershipStateLeft} {
|
||||
fixture.setMembershipState(t, organization.ID(), stored.ID, state)
|
||||
if _, _, err := fixture.read(stored.ID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("GetForMember(%s member) error = %v, want ErrOrganizationNotFound", state, err)
|
||||
}
|
||||
// The membership row is still readable in any state for the
|
||||
// application that manages members.
|
||||
membership, err := fixture.getMembership(organization.ID(), stored.ID)
|
||||
if err != nil || membership.State() != state || membership.GrantsAccess() {
|
||||
t.Fatalf("Get(%s membership) = %+v, %v, want the stored state without access", state, membership, err)
|
||||
}
|
||||
}
|
||||
fixture.setMembershipState(t, organization.ID(), stored.ID, domain.MembershipStateActive)
|
||||
if _, _, err := fixture.read(stored.ID, organization.ID()); err != nil {
|
||||
t.Fatalf("GetForMember(restored member) error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("updates the profile over the version read and never touches the verification", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Старое Имя"), now)
|
||||
later := now.Add(time.Hour)
|
||||
|
||||
changed := mustOrganizationProfile(t, domain.OrganizationProfileInput{
|
||||
Name: "ООО Новое Имя",
|
||||
Contacts: domain.OrganizationContactsInput{Telegram: "@new_careers"},
|
||||
Representatives: []domain.OrganizationRepresentativeInput{
|
||||
{Name: "Виктор Новый", JobTitle: "Директор"},
|
||||
},
|
||||
})
|
||||
updated := fixture.update(t, owner.ID, organization, changed, later)
|
||||
if updated.Version() != 2 || updated.Profile().Name() != "ООО Новое Имя" || !updated.UpdatedAt().Equal(later) || !updated.CreatedAt().Equal(now) {
|
||||
t.Fatalf("updated = %v, want version 2 with the new name at the new time", updated)
|
||||
}
|
||||
read, _, err := fixture.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("GetForMember() error = %v", err)
|
||||
}
|
||||
profile := read.Profile()
|
||||
if !profile.Equal(changed) || profile.Description() != "" || profile.Sphere() != "" || profile.Contacts().Website() != "" ||
|
||||
profile.Contacts().Telegram() != "@new_careers" || len(profile.Representatives()) != 1 {
|
||||
t.Fatalf("stored profile = %+v, want the replaced profile with the cleared fields unset", profile)
|
||||
}
|
||||
if read.Version() != 2 || !sameVerification(read.Verification(), organization.Verification()) {
|
||||
t.Fatalf("stored organization = %v, want version 2 and the unchanged verification", read)
|
||||
}
|
||||
|
||||
// A level that a verification process set stays through profile edits.
|
||||
if _, err := pool.Exec(ctx, `
|
||||
UPDATE organizations
|
||||
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
|
||||
WHERE id = $1`, organization.ID(), later); err != nil {
|
||||
t.Fatalf("simulate a verification process: %v", err)
|
||||
}
|
||||
again := fixture.update(t, owner.ID, read, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "ООО Третье Имя"}), later.Add(time.Hour))
|
||||
if again.Version() != 3 || again.Verification().Level() != domain.OrganizationVerificationE1 ||
|
||||
again.Verification().Basis() != domain.OrganizationBasisCorporateDomain || !again.Verification().ChangedAt().Equal(later) {
|
||||
t.Fatalf("after the profile edit = %v, want version 3 and the level e1 set by the process", again)
|
||||
}
|
||||
var level, basis string
|
||||
if err := pool.QueryRow(ctx, `SELECT verification_level, verification_basis FROM organizations WHERE id = $1`, organization.ID()).Scan(&level, &basis); err != nil ||
|
||||
level != "e1" || basis != "corporate_domain" {
|
||||
t.Fatalf("stored verification = %s %s, %v, want e1 corporate_domain", level, basis, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a stale version, a non-manager, and a non-member change nothing", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
recruiter := fixture.employer(t, "recruiter@example.com")
|
||||
suspendedOwner := fixture.employer(t, "suspended@example.com")
|
||||
outsider := fixture.employer(t, "outsider@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
fixture.addMember(t, organization, recruiter, domain.OrganizationRoleRecruiter, now.Add(time.Minute))
|
||||
fixture.addMember(t, organization, suspendedOwner, domain.OrganizationRoleOwner, now.Add(time.Minute))
|
||||
fixture.setMembershipState(t, organization.ID(), suspendedOwner.ID, domain.MembershipStateSuspended)
|
||||
changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Чужая правка"}), now.Add(time.Hour))
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyProfile() error = %v", err)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
actorID uuid.UUID
|
||||
want error
|
||||
}{
|
||||
{"a recruiter", recruiter.ID, outbound.ErrOrganizationManagerRequired},
|
||||
{"a suspended owner", suspendedOwner.ID, outbound.ErrOrganizationNotFound},
|
||||
{"an account that is no member", outsider.ID, outbound.ErrOrganizationNotFound},
|
||||
{"an unknown account", uuid.New(), outbound.ErrOrganizationNotFound},
|
||||
} {
|
||||
_, err := fixture.tryUpdate(test.actorID, changed)
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("UpdateProfile(%s) error = %v, want %v", test.name, err, test.want)
|
||||
}
|
||||
}
|
||||
|
||||
// Two owners read version 1; the second write is stale.
|
||||
first := fixture.update(t, owner.ID, organization, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Первая правка"}), now.Add(time.Hour))
|
||||
if first.Version() != 2 {
|
||||
t.Fatalf("first update version = %d, want 2", first.Version())
|
||||
}
|
||||
if _, err := fixture.tryUpdate(owner.ID, changed); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
|
||||
t.Fatalf("UpdateProfile(stale version) error = %v, want ErrOrganizationVersionConflict", err)
|
||||
}
|
||||
// The order of the checks: an outsider with a stale version learns
|
||||
// nothing about the version.
|
||||
if _, err := fixture.tryUpdate(outsider.ID, changed); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("UpdateProfile(outsider, stale version) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
|
||||
read, _, err := fixture.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("GetForMember() error = %v", err)
|
||||
}
|
||||
if read.Profile().Name() != "Первая правка" || read.Version() != 2 || len(read.Profile().Representatives()) != 0 {
|
||||
t.Fatalf("stored organization = %v, want only the first update", read)
|
||||
}
|
||||
|
||||
for name, build := range map[string]func() (domain.Organization, uuid.UUID){
|
||||
"a zero organization": func() (domain.Organization, uuid.UUID) { return domain.Organization{}, owner.ID },
|
||||
"a nil actor": func() (domain.Organization, uuid.UUID) { return read, uuid.Nil },
|
||||
} {
|
||||
organization, actor := build()
|
||||
if _, err := fixture.tryUpdate(actor, organization); !errors.Is(err, domain.ErrInvalidOrganization) {
|
||||
t.Fatalf("UpdateProfile(%s) error = %v, want ErrInvalidOrganization", name, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("of concurrent updates from one version exactly one wins", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, concurrentOrganizationUpdates+1))
|
||||
|
||||
errs := make([]error, concurrentOrganizationUpdates)
|
||||
start := make(chan struct{})
|
||||
var group sync.WaitGroup
|
||||
for index := range concurrentOrganizationUpdates {
|
||||
group.Go(func() {
|
||||
<-start
|
||||
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
|
||||
Name: "Правка " + string(rune('А'+index)),
|
||||
Representatives: []domain.OrganizationRepresentativeInput{
|
||||
{Name: "Автор " + string(rune('А'+index)), JobTitle: "Должность"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
errs[index] = err
|
||||
return
|
||||
}
|
||||
changed, err := organization.ApplyProfile(profile, now.Add(time.Hour))
|
||||
if err != nil {
|
||||
errs[index] = err
|
||||
return
|
||||
}
|
||||
errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := unit.Organizations().UpdateProfile(ctx, owner.ID, changed)
|
||||
return err
|
||||
})
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
|
||||
successes := 0
|
||||
for index, err := range errs {
|
||||
switch {
|
||||
case err == nil:
|
||||
successes++
|
||||
case errors.Is(err, outbound.ErrOrganizationVersionConflict):
|
||||
default:
|
||||
t.Fatalf("update %d error = %v, want nil or ErrOrganizationVersionConflict", index, err)
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("%d updates succeeded, want exactly 1", successes)
|
||||
}
|
||||
read, _, err := fixture.read(owner.ID, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("GetForMember() error = %v", err)
|
||||
}
|
||||
// The winner's name and representative belong together.
|
||||
winner := strings.TrimPrefix(read.Profile().Name(), "Правка ")
|
||||
if read.Version() != 2 || len(read.Profile().Representatives()) != 1 || read.Profile().Representatives()[0].Name() != "Автор "+winner {
|
||||
t.Fatalf("stored organization = %v, want one winner's name and representative at version 2", read)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a revocation that commits while an update waits stops the update", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
second := fixture.employer(t, "second@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
fixture.addMember(t, organization, second, domain.OrganizationRoleOwner, now.Add(time.Minute))
|
||||
changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Правка отозванного"}), now.Add(time.Hour))
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyProfile() error = %v", err)
|
||||
}
|
||||
|
||||
// A transaction revokes the second owner and stays open, holding the
|
||||
// row lock of the membership.
|
||||
revoker := startHeldTransaction(ctx, t, fixture.transactor, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
tx, _ := postgresadapter.TransactionForIntegrationTest(unit)
|
||||
_, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organization.ID(), second.ID)
|
||||
return err
|
||||
}, true)
|
||||
revoker.awaitHeld(ctx, t)
|
||||
|
||||
const applicationName = "organization-update-waiter"
|
||||
waiting := postgresadapter.NewTransactor(env.newPoolWithApplicationName(ctx, t, applicationName))
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
result <- waiting.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := unit.Organizations().UpdateProfile(ctx, second.ID, changed)
|
||||
return err
|
||||
})
|
||||
}()
|
||||
if event, ok := waitForLockWait(ctx, pool, applicationName); !ok {
|
||||
t.Fatalf("the update did not wait for the membership lock, last wait event %q", event)
|
||||
}
|
||||
if err := revoker.finish(); err != nil {
|
||||
t.Fatalf("revoking transaction error = %v", err)
|
||||
}
|
||||
|
||||
// The update saw the committed revocation and wrote nothing.
|
||||
if err := <-result; !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("UpdateProfile(revoked while waiting) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
read, _, err := fixture.read(owner.ID, organization.ID())
|
||||
if err != nil || read.Version() != 1 || read.Profile().Name() != "ООО Пример" {
|
||||
t.Fatalf("stored organization = %v, %v, want it unchanged at version 1", read, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keeps the role off the organization and refuses malformed rows", func(t *testing.T) {
|
||||
reset(t)
|
||||
// The role and the members live only in memberships.
|
||||
var columns []string
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'organizations' ORDER BY ordinal_position`)
|
||||
if err != nil {
|
||||
t.Fatalf("list organization columns: %v", err)
|
||||
}
|
||||
columns, err = pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
t.Fatalf("read organization columns: %v", err)
|
||||
}
|
||||
for _, column := range columns {
|
||||
if strings.Contains(column, "role") || strings.Contains(column, "owner") || strings.Contains(column, "member") || strings.Contains(column, "user") {
|
||||
t.Fatalf("organizations has the column %q; roles and members belong to memberships", column)
|
||||
}
|
||||
}
|
||||
|
||||
user := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
insertOrganization := func(name, verificationLevel, basis string, version int) error {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO organizations (
|
||||
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5)`, uuid.New(), name, verificationLevel, basis, now, version)
|
||||
return err
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
err error
|
||||
constraint string
|
||||
}{
|
||||
{"empty name", insertOrganization("", "e0", "confirmed_email", 1), "organizations_name_format"},
|
||||
{"padded name", insertOrganization(" ООО", "e0", "confirmed_email", 1), "organizations_name_format"},
|
||||
{"name with a line break", insertOrganization("ООО\nПример", "e0", "confirmed_email", 1), "organizations_name_format"},
|
||||
{"name over 200 characters", insertOrganization(strings.Repeat("я", 201), "e0", "confirmed_email", 1), "organizations_name_format"},
|
||||
{"unknown level", insertOrganization("ООО", "e4", "confirmed_email", 1), "organizations_verification_known"},
|
||||
{"level with the basis of another", insertOrganization("ООО", "e0", "corporate_domain", 1), "organizations_verification_known"},
|
||||
{"version zero", insertOrganization("ООО", "e0", "confirmed_email", 0), "organizations_version_positive"},
|
||||
} {
|
||||
assertSQLError(t, test.name, test.err, organizationCheckViolation, test.constraint)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
column string
|
||||
value string
|
||||
constraint string
|
||||
}{
|
||||
{"description with a padded end", "description", "текст ", "organizations_description_format"},
|
||||
{"description with a control character", "description", "текст\x07", "organizations_description_format"},
|
||||
{"sphere with a line break", "sphere", "а\nб", "organizations_sphere_format"},
|
||||
{"website over http", "contact_website", "http://example.com", "organizations_contact_website_format"},
|
||||
{"website with credentials", "contact_website", "https://user@example.com", "organizations_contact_website_format"},
|
||||
{"email with a space", "contact_email", "a b@example.com", "organizations_contact_email_format"},
|
||||
{"phone without a plus", "contact_phone", "74950000000", "organizations_contact_phone_format"},
|
||||
{"telegram without an at sign", "contact_telegram", "careers_team", "organizations_contact_telegram_format"},
|
||||
} {
|
||||
_, err := pool.Exec(ctx, `UPDATE organizations SET `+test.column+` = $2 WHERE id = $1`, organization.ID(), test.value)
|
||||
assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint)
|
||||
}
|
||||
// Each level takes its own bases, and the composite key of the
|
||||
// memberships can be the target of a later foreign key.
|
||||
for _, test := range []struct {
|
||||
level, basis string
|
||||
ok bool
|
||||
}{
|
||||
{"e1", "corporate_domain", true},
|
||||
{"e2", "requisites_and_authority", true},
|
||||
{"e3", "manual_review", true},
|
||||
{"e3", "partner_status", true},
|
||||
{"e2", "manual_review", false},
|
||||
{"e2", "corporate_domain", false},
|
||||
{"e3", "requisites_and_authority", false},
|
||||
{"e3", "confirmed_email", false},
|
||||
{"e1", "partner_status", false},
|
||||
} {
|
||||
_, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = $2, verification_basis = $3 WHERE id = $1`, organization.ID(), test.level, test.basis)
|
||||
if test.ok && err != nil {
|
||||
t.Fatalf("level %s with basis %s error = %v, want it accepted", test.level, test.basis, err)
|
||||
}
|
||||
if !test.ok {
|
||||
assertSQLError(t, "level "+test.level+" with basis "+test.basis, err, organizationCheckViolation, "organizations_verification_known")
|
||||
}
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = 'e0', verification_basis = 'confirmed_email' WHERE id = $1`, organization.ID()); err != nil {
|
||||
t.Fatalf("reset the level: %v", err)
|
||||
}
|
||||
composite, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin: %v", err)
|
||||
}
|
||||
defer func() { _ = composite.Rollback(ctx) }()
|
||||
if _, err := composite.Exec(ctx, `
|
||||
CREATE TABLE membership_reference (
|
||||
organization_id uuid NOT NULL,
|
||||
membership_id uuid NOT NULL,
|
||||
FOREIGN KEY (organization_id, membership_id) REFERENCES memberships (organization_id, id)
|
||||
)`); err != nil {
|
||||
t.Fatalf("composite foreign key on memberships: %v", err)
|
||||
}
|
||||
if _, err := composite.Exec(ctx, `
|
||||
INSERT INTO membership_reference SELECT organization_id, id FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil {
|
||||
t.Fatalf("reference a membership of its own organization: %v", err)
|
||||
}
|
||||
if _, err := composite.Exec(ctx, `
|
||||
INSERT INTO membership_reference SELECT $1::uuid, id FROM memberships WHERE organization_id = $2`, uuid.New(), organization.ID()); err == nil {
|
||||
t.Fatal("a membership was referenced under another organization")
|
||||
}
|
||||
_ = composite.Rollback(ctx)
|
||||
|
||||
// A value in the contract format passes.
|
||||
if _, err := pool.Exec(ctx, `UPDATE organizations SET contact_website = 'https://example.com/path?q=1', contact_phone = '+74950000000' WHERE id = $1`, organization.ID()); err != nil {
|
||||
t.Fatalf("update with valid contacts: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `UPDATE organizations SET updated_at = created_at - interval '1 second' WHERE id = $1`, organization.ID())
|
||||
assertSQLError(t, "update before creation", err, organizationCheckViolation, "organizations_timestamps_after_creation")
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
role string
|
||||
state string
|
||||
constraint string
|
||||
}{
|
||||
{"unknown role", "admin", "active", "memberships_role_known"},
|
||||
{"manager as a role of the PRD wording", "manager", "active", "memberships_role_known"},
|
||||
{"unknown state", "recruiter", "invited", "memberships_state_known"},
|
||||
} {
|
||||
second := fixture.employer(t, test.role+test.state+"@example.com")
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organization.ID(), second.ID, test.role, test.state, now)
|
||||
assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO organization_representatives (organization_id, ordinal, name, job_title)
|
||||
VALUES ($1, 10, 'Имя', 'Должность')`, organization.ID())
|
||||
assertSQLError(t, "eleventh representative", err, organizationCheckViolation, "organization_representatives_ordinal_range")
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO organization_representatives (organization_id, ordinal, name, job_title)
|
||||
VALUES ($1, 5, 'Имя', ' Должность')`, organization.ID())
|
||||
assertSQLError(t, "padded job title", err, organizationCheckViolation, "organization_representatives_job_title_format")
|
||||
})
|
||||
|
||||
t.Run("an account and an organization with memberships cannot be deleted", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
|
||||
|
||||
_, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, owner.ID)
|
||||
assertSQLError(t, "delete of an account with a membership", err, organizationRestrictViolation, "memberships_user_id_fkey")
|
||||
_, err = pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID())
|
||||
assertSQLError(t, "delete of an organization with a member", err, organizationRestrictViolation, "memberships_organization_id_fkey")
|
||||
assertRowCount(ctx, t, pool, organizationsTable, 1)
|
||||
assertRowCount(ctx, t, pool, membershipsTable, 1)
|
||||
|
||||
// Once the memberships are gone the representatives go with the
|
||||
// organization.
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil {
|
||||
t.Fatalf("delete the memberships: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID()); err != nil {
|
||||
t.Fatalf("delete the organization: %v", err)
|
||||
}
|
||||
assertRowCount(ctx, t, pool, organizationRepresentativesTable, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) employer(t *testing.T, email string) domain.User {
|
||||
t.Helper()
|
||||
return fixture.identity.createUser(t, email, domain.ScenarioEmployer, fixture.now.Add(-time.Hour))
|
||||
}
|
||||
|
||||
func mustOrganizationProfile(t *testing.T, input domain.OrganizationProfileInput) domain.OrganizationProfile {
|
||||
t.Helper()
|
||||
profile, err := domain.NewOrganizationProfile(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v", err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) completeProfile(t *testing.T, name string) domain.OrganizationProfile {
|
||||
t.Helper()
|
||||
return mustOrganizationProfile(t, domain.OrganizationProfileInput{
|
||||
Name: name,
|
||||
Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.",
|
||||
Sphere: "Платежи и финансовые сервисы",
|
||||
Contacts: domain.OrganizationContactsInput{
|
||||
Website: "https://payments.example.com", Email: "careers@payments.example.com", Phone: "+74950000000", Telegram: "@payments_careers",
|
||||
},
|
||||
Representatives: []domain.OrganizationRepresentativeInput{
|
||||
{Name: "Анна Тестова", JobTitle: "Руководитель по подбору"},
|
||||
{Name: "Борис Образцов", JobTitle: "Технический директор"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) newOrganization(t *testing.T, profile domain.OrganizationProfile, at time.Time) domain.Organization {
|
||||
t.Helper()
|
||||
organization, err := domain.NewOrganization(profile, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
// create stores an organization with its owner in one transaction.
|
||||
func (fixture organizationFixture) create(t *testing.T, owner domain.User, profile domain.OrganizationProfile, at time.Time) domain.Organization {
|
||||
t.Helper()
|
||||
organization := fixture.newOrganization(t, profile, at)
|
||||
membership, err := domain.NewOwnerMembership(organization.ID(), owner.ID, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Organizations().CreateWithOwner(ctx, organization, membership)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateWithOwner(%q) error = %v", profile.Name(), err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) addMember(t *testing.T, organization domain.Organization, user domain.User, role domain.OrganizationRole, at time.Time) {
|
||||
t.Helper()
|
||||
membership, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: user.ID, Role: role, At: at})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Memberships().Insert(ctx, membership)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Insert(%s membership) error = %v", role, err)
|
||||
}
|
||||
}
|
||||
|
||||
// setMembershipState ends or restores a membership the way the planned
|
||||
// member management will; the repository has no such method yet.
|
||||
func (fixture organizationFixture) setMembershipState(t *testing.T, organizationID, userID uuid.UUID, state domain.MembershipState) {
|
||||
t.Helper()
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `UPDATE memberships SET state = $3 WHERE organization_id = $1 AND user_id = $2`, organizationID, userID, string(state)); err != nil {
|
||||
t.Fatalf("set the membership state to %s: %v", state, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) read(userID, organizationID uuid.UUID) (domain.Organization, domain.Membership, error) {
|
||||
var (
|
||||
organization domain.Organization
|
||||
membership domain.Membership
|
||||
)
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
organization, membership, err = unit.Organizations().GetForMember(ctx, organizationID, userID)
|
||||
return err
|
||||
})
|
||||
return organization, membership, err
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) getMembership(organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
var membership domain.Membership
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
membership, err = unit.Memberships().Get(ctx, organizationID, userID)
|
||||
return err
|
||||
})
|
||||
return membership, err
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) list(t *testing.T, query outbound.OrganizationListQuery) outbound.OrganizationPage {
|
||||
t.Helper()
|
||||
var page outbound.OrganizationPage
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
page, err = unit.Organizations().ListForUser(ctx, query)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ListForUser() error = %v", err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// update applies profile to organization as of its version and stores it.
|
||||
func (fixture organizationFixture) update(
|
||||
t *testing.T,
|
||||
actorID uuid.UUID,
|
||||
organization domain.Organization,
|
||||
profile domain.OrganizationProfile,
|
||||
at time.Time,
|
||||
) domain.Organization {
|
||||
t.Helper()
|
||||
changed, err := organization.ApplyProfile(profile, at)
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyProfile() error = %v", err)
|
||||
}
|
||||
updated, err := fixture.tryUpdate(actorID, changed)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateProfile() error = %v", err)
|
||||
}
|
||||
return updated
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) tryUpdate(actorID uuid.UUID, organization domain.Organization) (domain.Organization, error) {
|
||||
var updated domain.Organization
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
updated, err = unit.Organizations().UpdateProfile(ctx, actorID, organization)
|
||||
return err
|
||||
})
|
||||
return updated, err
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) assertNothingStored(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, table := range organizationTables {
|
||||
assertRowCount(fixture.ctx, t, fixture.pool, table, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func organizationIDs(page outbound.OrganizationPage) []uuid.UUID {
|
||||
ids := make([]uuid.UUID, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
ids = append(ids, item.Organization.ID())
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// sameVerification compares the instants, because a stored time carries
|
||||
// another location than the application clock that wrote it.
|
||||
func sameVerification(left, right domain.OrganizationVerification) bool {
|
||||
return left.Level() == right.Level() && left.Basis() == right.Basis() && left.ChangedAt().Equal(right.ChangedAt())
|
||||
}
|
||||
@@ -143,7 +143,9 @@ func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testi
|
||||
}
|
||||
|
||||
// truncateTables resets shared tables between sequential subtests. Callers
|
||||
// must not run subtests that use these tables in parallel.
|
||||
// must not run subtests that use these tables in parallel. PostgreSQL refuses
|
||||
// to truncate a table that another table references unless both are listed,
|
||||
// so a test that truncates users names usersDependentTables.
|
||||
func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) {
|
||||
t.Helper()
|
||||
names := make([]string, 0, len(tables))
|
||||
|
||||
@@ -33,10 +33,14 @@ const (
|
||||
mailQuotaMigrationVersion = 7
|
||||
// scheduledJobMigrationVersion creates scheduledJobTableNames.
|
||||
scheduledJobMigrationVersion = 8
|
||||
// organizationMigrationVersion creates organizationTableNames and
|
||||
// organizationFunctionNames.
|
||||
organizationMigrationVersion = 10
|
||||
)
|
||||
|
||||
var (
|
||||
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, and 00008.
|
||||
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, 00008, and
|
||||
// 00010.
|
||||
outboxTables = []string{"outbox_events"}
|
||||
identityTableNames = []string{"users", "email_tokens", "sessions"}
|
||||
policyTableNames = []string{"policy_versions"}
|
||||
@@ -44,9 +48,12 @@ var (
|
||||
deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"}
|
||||
mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"}
|
||||
scheduledJobTableNames = []string{"scheduled_jobs"}
|
||||
// Trigger functions created by 00003 and 00006.
|
||||
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
|
||||
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
|
||||
// organizationTableNames lists the tables of migration 00010.
|
||||
organizationTableNames = []string{"organizations", "organization_representatives", "memberships"}
|
||||
// Trigger functions created by 00003, 00006, and 00010.
|
||||
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
|
||||
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
|
||||
organizationFunctionNames = []string{"organizations_require_owner()"}
|
||||
)
|
||||
|
||||
func TestPostgresMigrations(t *testing.T) {
|
||||
@@ -80,9 +87,11 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, scheduledJobTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
|
||||
|
||||
identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false
|
||||
scheduledJobRolledBack := false
|
||||
scheduledJobRolledBack, organizationRolledBack := false, false
|
||||
for rolledBack := 0; ; rolledBack++ {
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
|
||||
@@ -94,6 +103,14 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
|
||||
}
|
||||
if result.Version == organizationMigrationVersion {
|
||||
// The organization migration removes its tables and its
|
||||
// function and leaves the identity tables they reference.
|
||||
assertTablesExist(ctx, t, pool, false, organizationTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, false, organizationFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, identityTableNames...)
|
||||
organizationRolledBack = true
|
||||
}
|
||||
if result.Version == scheduledJobMigrationVersion {
|
||||
// The scheduled job migration removes only its own table.
|
||||
assertTablesExist(ctx, t, pool, false, scheduledJobTableNames...)
|
||||
@@ -137,10 +154,11 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
identityRolledBack = true
|
||||
}
|
||||
}
|
||||
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack || !scheduledJobRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, %d, and %d were not all rolled back",
|
||||
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack ||
|
||||
!scheduledJobRolledBack || !organizationRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, %d, %d, and %d were not all rolled back",
|
||||
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion,
|
||||
scheduledJobMigrationVersion)
|
||||
scheduledJobMigrationVersion, organizationMigrationVersion)
|
||||
}
|
||||
assertTablesExist(ctx, t, pool, false, outboxTables...)
|
||||
assertTablesExist(ctx, t, pool, false, identityTableNames...)
|
||||
@@ -181,6 +199,8 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, consumerTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
|
||||
assertAllApplied(ctx, t, migrator, total)
|
||||
})
|
||||
|
||||
|
||||
@@ -17,20 +17,22 @@ import (
|
||||
)
|
||||
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"\\S": ogenregex.MustCompile("\\S"),
|
||||
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
|
||||
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
|
||||
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
|
||||
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
|
||||
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
|
||||
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
|
||||
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
|
||||
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
|
||||
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
|
||||
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
|
||||
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
|
||||
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
|
||||
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
|
||||
"\\S": ogenregex.MustCompile("\\S"),
|
||||
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
|
||||
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
|
||||
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
|
||||
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
|
||||
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
|
||||
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
|
||||
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
|
||||
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
|
||||
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
|
||||
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
|
||||
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
|
||||
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
|
||||
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
|
||||
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
|
||||
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
|
||||
}
|
||||
var (
|
||||
// Allocate option closure once.
|
||||
|
||||
@@ -1342,6 +1342,263 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreateOrganizationRequest handles CreateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// POST /api/v1/organizations
|
||||
func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("CreateOrganization"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: CreateOrganizationOperation,
|
||||
ID: "CreateOrganization",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCsrf",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCsrf", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 1
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000011},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeCreateOrganizationParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeCreateOrganizationRequest(r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeRequestError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeRequest", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := close(); err != nil {
|
||||
recordError("CloseRequest", err)
|
||||
}
|
||||
}()
|
||||
|
||||
var response CreateOrganizationRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: CreateOrganizationOperation,
|
||||
OperationSummary: "Create an organization; the caller becomes its owner.",
|
||||
OperationID: "CreateOrganization",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}: params.IdempotencyKey,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *OrganizationCreate
|
||||
Params = CreateOrganizationParams
|
||||
Response = CreateOrganizationRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackCreateOrganizationParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.CreateOrganization(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.CreateOrganization(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeCreateOrganizationResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
@@ -4390,6 +4647,224 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationRequest handles GetOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}
|
||||
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetOrganization"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: GetOrganizationOperation,
|
||||
ID: "GetOrganization",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeGetOrganizationParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response GetOrganizationRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetOrganizationOperation,
|
||||
OperationSummary: "Read an organization of which the caller is a member.",
|
||||
OperationID: "GetOrganization",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetOrganizationParams
|
||||
Response = GetOrganizationRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetOrganizationParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetOrganization(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetOrganization(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeGetOrganizationResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -5670,6 +6145,233 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/me/organizations
|
||||
func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("ListMyOrganizations"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/organizations"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: ListMyOrganizationsOperation,
|
||||
ID: "ListMyOrganizations",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeListMyOrganizationsParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response ListMyOrganizationsRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: ListMyOrganizationsOperation,
|
||||
OperationSummary: "List the organizations available to the current account.",
|
||||
OperationID: "ListMyOrganizations",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}: params.Limit,
|
||||
{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}: params.Cursor,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = ListMyOrganizationsParams
|
||||
Response = ListMyOrganizationsRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackListMyOrganizationsParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.ListMyOrganizations(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.ListMyOrganizations(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeListMyOrganizationsResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMySupportCasesRequest handles ListMySupportCases operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
|
||||
@@ -8162,6 +8864,269 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpdateOrganizationRequest handles UpdateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// PATCH /api/v1/organizations/{org_id}
|
||||
func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("UpdateOrganization"),
|
||||
semconv.HTTPRequestMethodKey.String("PATCH"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: UpdateOrganizationOperation,
|
||||
ID: "UpdateOrganization",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCsrf",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCsrf", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 1
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000011},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeUpdateOrganizationParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeUpdateOrganizationRequest(r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeRequestError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeRequest", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := close(); err != nil {
|
||||
recordError("CloseRequest", err)
|
||||
}
|
||||
}()
|
||||
|
||||
var response UpdateOrganizationRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: UpdateOrganizationOperation,
|
||||
OperationSummary: "Change the profile of an organization.",
|
||||
OperationID: "UpdateOrganization",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *OrganizationUpdate
|
||||
Params = UpdateOrganizationParams
|
||||
Response = UpdateOrganizationRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackUpdateOrganizationParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.UpdateOrganization(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.UpdateOrganization(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeUpdateOrganizationResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
|
||||
@@ -29,6 +29,10 @@ type CreateOrganizationNeedRes interface {
|
||||
createOrganizationNeedRes()
|
||||
}
|
||||
|
||||
type CreateOrganizationRes interface {
|
||||
createOrganizationRes()
|
||||
}
|
||||
|
||||
type DeclineMyInvitationRes interface {
|
||||
declineMyInvitationRes()
|
||||
}
|
||||
@@ -85,6 +89,10 @@ type GetOrganizationNeedRes interface {
|
||||
getOrganizationNeedRes()
|
||||
}
|
||||
|
||||
type GetOrganizationRes interface {
|
||||
getOrganizationRes()
|
||||
}
|
||||
|
||||
type ListMyConsentsRes interface {
|
||||
listMyConsentsRes()
|
||||
}
|
||||
@@ -93,6 +101,10 @@ type ListMyInvitationsRes interface {
|
||||
listMyInvitationsRes()
|
||||
}
|
||||
|
||||
type ListMyOrganizationsRes interface {
|
||||
listMyOrganizationsRes()
|
||||
}
|
||||
|
||||
type ListMySupportCasesRes interface {
|
||||
listMySupportCasesRes()
|
||||
}
|
||||
@@ -145,6 +157,10 @@ type UpdateOrganizationNeedRes interface {
|
||||
updateOrganizationNeedRes()
|
||||
}
|
||||
|
||||
type UpdateOrganizationRes interface {
|
||||
updateOrganizationRes()
|
||||
}
|
||||
|
||||
type ViewMyInvitationRes interface {
|
||||
viewMyInvitationRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@ const (
|
||||
ConfirmEmailOperation OperationName = "ConfirmEmail"
|
||||
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
|
||||
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
|
||||
CreateOrganizationOperation OperationName = "CreateOrganization"
|
||||
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
|
||||
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
|
||||
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
|
||||
@@ -25,12 +26,14 @@ const (
|
||||
GetMyInvitationOperation OperationName = "GetMyInvitation"
|
||||
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
|
||||
GetMySupportCaseOperation OperationName = "GetMySupportCase"
|
||||
GetOrganizationOperation OperationName = "GetOrganization"
|
||||
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
|
||||
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
|
||||
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
|
||||
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
|
||||
ListMyConsentsOperation OperationName = "ListMyConsents"
|
||||
ListMyInvitationsOperation OperationName = "ListMyInvitations"
|
||||
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
|
||||
ListMySupportCasesOperation OperationName = "ListMySupportCases"
|
||||
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
|
||||
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
|
||||
@@ -42,6 +45,7 @@ const (
|
||||
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
|
||||
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
|
||||
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
|
||||
UpdateOrganizationOperation OperationName = "UpdateOrganization"
|
||||
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
|
||||
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
|
||||
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
|
||||
|
||||
@@ -503,6 +503,100 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// CreateOrganizationParams is parameters of CreateOrganization operation.
|
||||
type CreateOrganizationParams struct {
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
|
||||
// request by method, path, and body.
|
||||
//
|
||||
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
|
||||
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
|
||||
// not_found or 409 state_conflict. A replay does not repeat the side effect.
|
||||
//
|
||||
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
|
||||
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
|
||||
// precondition_required (nothing changed; read the resource again and retry), 422
|
||||
// idempotency_key_reused, 429, and every 5xx.
|
||||
//
|
||||
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
|
||||
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
|
||||
// before any other key check; a running request with the same fingerprint returns 409
|
||||
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
|
||||
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
|
||||
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func unpackCreateOrganizationParams(packed middleware.Parameters) (params CreateOrganizationParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}
|
||||
params.IdempotencyKey = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeCreateOrganizationParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateOrganizationParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode header: Idempotency-Key.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Idempotency-Key",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.IdempotencyKey = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 255,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.IdempotencyKey)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation.
|
||||
type CreateOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -1447,6 +1541,75 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationParams is parameters of GetOrganization operation.
|
||||
type GetOrganizationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
// this organization, checked by the server on every request; the identifier itself grants nothing. An
|
||||
// organization without such a membership and an unknown identifier both answer 404 not_found, so
|
||||
// organizations cannot be enumerated.
|
||||
OrgID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackGetOrganizationParams(packed middleware.Parameters) (params GetOrganizationParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetOrganizationParams, _ error) {
|
||||
// Decode path: org_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "org_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.OrgID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
|
||||
type GetOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -2238,6 +2401,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
|
||||
type ListMyOrganizationsParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
// `page.has_more` to detect the end.
|
||||
Limit OptInt32 `json:",omitempty,omitzero"`
|
||||
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
|
||||
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListMyOrganizationsParams(packed middleware.Parameters) (params ListMyOrganizationsParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt32)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyOrganizationsParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int32(20)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int32
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt32(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 512,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9_-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMySupportCasesParams is parameters of ListMySupportCases operation.
|
||||
type ListMySupportCasesParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
@@ -3535,6 +3874,75 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// UpdateOrganizationParams is parameters of UpdateOrganization operation.
|
||||
type UpdateOrganizationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
// this organization, checked by the server on every request; the identifier itself grants nothing. An
|
||||
// organization without such a membership and an unknown identifier both answer 404 not_found, so
|
||||
// organizations cannot be enumerated.
|
||||
OrgID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackUpdateOrganizationParams(packed middleware.Parameters) (params UpdateOrganizationParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeUpdateOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationParams, _ error) {
|
||||
// Decode path: org_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "org_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.OrgID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation.
|
||||
type UpdateOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
|
||||
@@ -409,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateOrganizationRequest(r *http.Request) (
|
||||
req *OrganizationCreate,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request OrganizationCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
|
||||
req *OrganizationInvitationCreate,
|
||||
rawBody []byte,
|
||||
@@ -1278,6 +1357,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeUpdateOrganizationRequest(r *http.Request) (
|
||||
req *OrganizationUpdate,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request OrganizationUpdate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
|
||||
req *OrganizationInvitationUpdate,
|
||||
rawBody []byte,
|
||||
|
||||
@@ -657,6 +657,133 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R
|
||||
}
|
||||
}
|
||||
|
||||
func encodeCreateOrganizationResponse(response CreateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(201)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *CreateOrganizationBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *CreateOrganizationUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *CreateOrganizationForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *CreateOrganizationConflict:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(409)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *CreateOrganizationUnprocessableEntity:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(422)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -1769,6 +1896,89 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -2161,6 +2371,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
|
||||
}
|
||||
}
|
||||
|
||||
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *MyOrganizationListHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyOrganizationsBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyOrganizationsUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyOrganizationsForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *SupportCaseListHeaders:
|
||||
@@ -3282,6 +3563,133 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes
|
||||
}
|
||||
}
|
||||
|
||||
func encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *UpdateOrganizationBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *UpdateOrganizationUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *UpdateOrganizationForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *UpdateOrganizationNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *UpdateOrganizationPreconditionFailed:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(412)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
CancelMyInvitationOperation: []string{},
|
||||
CreateMyAssessmentAttemptOperation: []string{},
|
||||
CreateMySupportCaseOperation: []string{},
|
||||
CreateOrganizationOperation: []string{},
|
||||
CreateOrganizationInvitationOperation: []string{},
|
||||
CreateOrganizationNeedOperation: []string{},
|
||||
DeclineMyInvitationOperation: []string{},
|
||||
@@ -72,11 +73,13 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
GetMyInvitationOperation: []string{},
|
||||
GetMyQuestionnaireOperation: []string{},
|
||||
GetMySupportCaseOperation: []string{},
|
||||
GetOrganizationOperation: []string{},
|
||||
GetOrganizationInvitationOperation: []string{},
|
||||
GetOrganizationInvitationContactsOperation: []string{},
|
||||
GetOrganizationNeedOperation: []string{},
|
||||
ListMyConsentsOperation: []string{},
|
||||
ListMyInvitationsOperation: []string{},
|
||||
ListMyOrganizationsOperation: []string{},
|
||||
ListMySupportCasesOperation: []string{},
|
||||
ListOrganizationInvitationsOperation: []string{},
|
||||
ListOrganizationNeedsOperation: []string{},
|
||||
@@ -85,6 +88,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
SaveMyQuestionnaireOperation: []string{},
|
||||
SendOrganizationInvitationOperation: []string{},
|
||||
SubmitMyAssessmentAnswerOperation: []string{},
|
||||
UpdateOrganizationOperation: []string{},
|
||||
UpdateOrganizationInvitationOperation: []string{},
|
||||
UpdateOrganizationNeedOperation: []string{},
|
||||
ViewMyInvitationOperation: []string{},
|
||||
@@ -118,6 +122,7 @@ var operationRolesSessionCsrf = map[string][]string{
|
||||
CancelMyInvitationOperation: []string{},
|
||||
CreateMyAssessmentAttemptOperation: []string{},
|
||||
CreateMySupportCaseOperation: []string{},
|
||||
CreateOrganizationOperation: []string{},
|
||||
CreateOrganizationInvitationOperation: []string{},
|
||||
CreateOrganizationNeedOperation: []string{},
|
||||
DeclineMyInvitationOperation: []string{},
|
||||
@@ -127,6 +132,7 @@ var operationRolesSessionCsrf = map[string][]string{
|
||||
SaveMyQuestionnaireOperation: []string{},
|
||||
SendOrganizationInvitationOperation: []string{},
|
||||
SubmitMyAssessmentAnswerOperation: []string{},
|
||||
UpdateOrganizationOperation: []string{},
|
||||
UpdateOrganizationInvitationOperation: []string{},
|
||||
UpdateOrganizationNeedOperation: []string{},
|
||||
ViewMyInvitationOperation: []string{},
|
||||
|
||||
@@ -253,6 +253,36 @@ type Handler interface {
|
||||
//
|
||||
// POST /api/v1/me/support-cases
|
||||
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
|
||||
// CreateOrganization implements CreateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// POST /api/v1/organizations
|
||||
CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (CreateOrganizationRes, error)
|
||||
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
@@ -608,6 +638,30 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/me/support-cases/{case_id}
|
||||
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
|
||||
// GetOrganization implements GetOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}
|
||||
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -765,6 +819,35 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/me/invitations
|
||||
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
|
||||
// ListMyOrganizations implements ListMyOrganizations operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/me/organizations
|
||||
ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error)
|
||||
// ListMySupportCases implements ListMySupportCases operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
|
||||
@@ -1086,6 +1169,42 @@ type Handler interface {
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
|
||||
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
|
||||
// UpdateOrganization implements UpdateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// PATCH /api/v1/organizations/{org_id}
|
||||
UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (UpdateOrganizationRes, error)
|
||||
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
|
||||
@@ -273,6 +273,39 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateOrganization implements CreateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// POST /api/v1/organizations
|
||||
func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (r CreateOrganizationRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
@@ -670,6 +703,33 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganization implements GetOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}
|
||||
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -845,6 +905,38 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMyOrganizations implements ListMyOrganizations operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// GET /api/v1/me/organizations
|
||||
func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (r ListMyOrganizationsRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMySupportCases implements ListMySupportCases operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
|
||||
@@ -1199,6 +1291,45 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UpdateOrganization implements UpdateOrganization operation.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// PATCH /api/v1/organizations/{org_id}
|
||||
func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (r UpdateOrganizationRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,576 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
)
|
||||
|
||||
// Organization request fixtures shared by the organization tests.
|
||||
const (
|
||||
myOrganizationsPath = "/api/v1/me/organizations"
|
||||
organizationsPath = "/api/v1/organizations"
|
||||
organizationPath = organizationsPath + "/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"
|
||||
|
||||
validOrganizationContacts = `{"website":"https://payments.example.com","email":"careers@payments.example.com","phone":"+74950000000","telegram":"@payments_careers"}`
|
||||
emptyOrganizationContacts = `{"website":null,"email":null,"phone":null,"telegram":null}`
|
||||
)
|
||||
|
||||
// organizationBody builds a JSON object from the given members.
|
||||
func organizationBody(members ...string) string {
|
||||
return "{" + strings.Join(members, ",") + "}"
|
||||
}
|
||||
|
||||
// The schemas alone must accept the profile a company may send and reject
|
||||
// what no request may carry: a role, an owner, a verification level or its
|
||||
// basis, the members, the card, a version, or an identifier. Security accepts
|
||||
// the session here, so the request reaches validation; a valid request then
|
||||
// answers 501 until the operations are implemented. The rules that need
|
||||
// storage, such as the website host or the version, pass the schema and are
|
||||
// checked by the server.
|
||||
func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
|
||||
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
|
||||
create := func(body string) identityRequest {
|
||||
return identityRequest{method: http.MethodPost, path: organizationsPath, body: body, headers: command}
|
||||
}
|
||||
update := func(members ...string) identityRequest {
|
||||
return identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(append([]string{`"expected_version":1`}, members...)...), headers: session}
|
||||
}
|
||||
forbiddenFields := []string{
|
||||
`"role":"owner"`,
|
||||
`"owner_id":"01928f7a-0000-7000-8000-00000000c0de"`,
|
||||
`"verification_level":"e1"`,
|
||||
`"verification":{"level":"e2","basis":"manual_review","changed_at":"2026-10-06T09:00:00Z"}`,
|
||||
`"verification_basis":"corporate_domain"`,
|
||||
`"members":[{"user_id":"01928f7a-0000-7000-8000-00000000c0de","role":"owner"}]`,
|
||||
`"membership":{"organization_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner","state":"active","joined_at":"2026-10-06T09:00:00Z"}`,
|
||||
`"candidate_card":{}`,
|
||||
`"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`,
|
||||
`"version":3`,
|
||||
`"created_at":"2026-10-06T09:00:00Z"`,
|
||||
}
|
||||
|
||||
type expectation struct {
|
||||
name string
|
||||
request identityRequest
|
||||
location api.ProblemFieldLocation
|
||||
pointer string
|
||||
code string
|
||||
}
|
||||
tests := make([]expectation, 0, 36+2*len(forbiddenFields))
|
||||
tests = append(tests, []expectation{
|
||||
{
|
||||
name: "list",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=20", headers: session},
|
||||
},
|
||||
{
|
||||
name: "list with a limit above the maximum",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=101", headers: session},
|
||||
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "list with a malformed cursor",
|
||||
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?cursor=not%20a%20cursor", headers: session},
|
||||
location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name only",
|
||||
request: create(organizationBody(`"name":"ООО Пример Платежи"`)),
|
||||
},
|
||||
{
|
||||
name: "create with a complete card",
|
||||
request: create(organizationBody(
|
||||
`"name":"ООО Пример Платежи"`,
|
||||
`"description":"Платежный сервис.\nСобственное ядро."`,
|
||||
`"sphere":"Платежи и финансовые сервисы"`,
|
||||
`"contacts":`+validOrganizationContacts,
|
||||
`"representatives":[{"name":"Анна Тестова","job_title":"Руководитель по подбору"}]`,
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "create with an explicit null description and sphere",
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, `"description":null`, `"sphere":null`, `"contacts":`+emptyOrganizationContacts, `"representatives":[]`)),
|
||||
},
|
||||
{
|
||||
// A domain rule of the server: the schema accepts any https
|
||||
// string without credentials, and the host rules come after it.
|
||||
name: "create with a website that has a port",
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, `"contacts":{"website":"https://payments.example.com:8443","email":null,"phone":null,"telegram":null}`)),
|
||||
},
|
||||
{
|
||||
name: "create without a name",
|
||||
request: create(organizationBody(`"sphere":"Платежи"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create without an Idempotency-Key",
|
||||
request: identityRequest{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: session},
|
||||
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create with an empty name",
|
||||
request: create(organizationBody(`"name":""`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name over 200 characters",
|
||||
request: create(organizationBody(`"name":"` + strings.Repeat("я", 201) + `"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name that has a leading space",
|
||||
request: create(organizationBody(`"name":" ООО"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a name that has a line break",
|
||||
request: create(organizationBody(`"name":"ООО\nПример"`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a sphere that has a trailing space",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"sphere":"Платежи "`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/sphere", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an empty description",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"description":""`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with contacts that omit a field",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "required",
|
||||
},
|
||||
{
|
||||
name: "create with a personal contact kind",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":null,"home_address":"ул. Тестовая"}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an http website",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"http://payments.example.com","email":null,"phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a website that has credentials",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"https://user:secret@payments.example.com","email":null,"phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a phone that is not E.164",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":"8 495 000-00-00","telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/phone", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a Telegram username without the at sign",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":"payments_careers"}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with an email that is not an address",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":"careers","phone":null,"telegram":null}`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts/email", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with eleven representatives",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[`+
|
||||
strings.TrimSuffix(strings.Repeat(`{"name":"Имя","job_title":"Должность"},`, 11), ",")+`]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
// A failure inside an array element during decoding reports the
|
||||
// pointer of the array, because jx reports no element index.
|
||||
name: "create with a representative that has no job title",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова"}]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create with a representative contact",
|
||||
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова","job_title":"HR","email":"anna@example.com"}]`)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with the version only",
|
||||
request: update(),
|
||||
},
|
||||
{
|
||||
name: "update of the profile with explicit nulls",
|
||||
request: update(`"description":null`, `"sphere":null`),
|
||||
},
|
||||
{
|
||||
name: "update of the contacts and representatives as a whole",
|
||||
request: update(`"contacts":`+emptyOrganizationContacts, `"representatives":[]`),
|
||||
},
|
||||
{
|
||||
name: "update without expected_version",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"name":"ООО Новое"`), headers: session},
|
||||
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
|
||||
},
|
||||
{
|
||||
name: "update with expected_version zero",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":0`), headers: session},
|
||||
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with a null name",
|
||||
request: update(`"name":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with null representatives",
|
||||
request: update(`"representatives":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update with null contacts",
|
||||
request: update(`"contacts":null`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "read",
|
||||
request: identityRequest{method: http.MethodGet, path: organizationPath, headers: session},
|
||||
},
|
||||
{
|
||||
name: "read an organization identifier that is not a UUID",
|
||||
request: identityRequest{method: http.MethodGet, path: organizationsPath + "/acme", headers: session},
|
||||
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "update an organization identifier that is not a UUID",
|
||||
request: identityRequest{method: http.MethodPatch, path: organizationsPath + "/acme", body: organizationBody(`"expected_version":1`), headers: session},
|
||||
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
|
||||
},
|
||||
}...)
|
||||
// No request of either command may carry a right or a trust level, each
|
||||
// one alone, as a whole-body rejection of an unknown field.
|
||||
for _, field := range forbiddenFields {
|
||||
tests = append(tests,
|
||||
expectation{
|
||||
name: "create with the forbidden field " + strings.SplitN(field, ":", 2)[0],
|
||||
request: create(organizationBody(`"name":"ООО Пример"`, field)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
expectation{
|
||||
name: "update with the forbidden field " + strings.SplitN(field, ":", 2)[0],
|
||||
request: update(field),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
response := serveIdentityRequest(t, router, test.request)
|
||||
|
||||
switch test.code {
|
||||
case "":
|
||||
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
|
||||
default:
|
||||
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
|
||||
for _, field := range body.Errors {
|
||||
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Every organization operation requires an employer session; DenyAllSecurity
|
||||
// grants none, with or without a cookie and a CSRF token, and no request can
|
||||
// name another account.
|
||||
func TestOrganizationAccessBeforeImplementation(t *testing.T) {
|
||||
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
|
||||
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
|
||||
for _, test := range []identityRequest{
|
||||
{method: http.MethodGet, path: myOrganizationsPath},
|
||||
{method: http.MethodGet, path: myOrganizationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodGet, path: myOrganizationsPath + "?user_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: command},
|
||||
{method: http.MethodGet, path: organizationPath},
|
||||
{method: http.MethodGet, path: organizationPath, headers: map[string]string{"Cookie": testSessionCookie}},
|
||||
{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":1`, `"name":"ООО Новое"`), headers: session},
|
||||
} {
|
||||
t.Run(test.method+" "+test.path, func(t *testing.T) {
|
||||
router := newTestRouter(t, func(context.Context) error { return nil })
|
||||
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A role and a verification level never travel in the company DTOs: not in
|
||||
// the response a member reads, not in the create or the update body. The
|
||||
// role lives in OrganizationMembership, which a client cannot send, and the
|
||||
// level in OrganizationVerification, which only the response carries.
|
||||
func TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests(t *testing.T) {
|
||||
raising := []string{
|
||||
"role", "roles", "verification", "verification_level", "verification_basis", "level", "basis", "trust_level",
|
||||
"owner", "owner_id", "members", "membership", "user_id", "account_id", "permissions", "e0", "e1", "e2", "e3",
|
||||
}
|
||||
for _, dto := range []any{api.Organization{}, api.OrganizationCreate{}, api.OrganizationUpdate{}, api.CandidateOrganizationCard{}, api.OrganizationContactChannels{}, api.OrganizationRepresentative{}} {
|
||||
typ := reflect.TypeOf(dto)
|
||||
for i := range typ.NumField() {
|
||||
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
|
||||
isVerificationReadModel := (typ == reflect.TypeFor[api.Organization]() && name == "verification") ||
|
||||
(typ == reflect.TypeFor[api.CandidateOrganizationCard]() && name == "verification_level")
|
||||
for _, field := range raising {
|
||||
if name == field && !isVerificationReadModel {
|
||||
t.Errorf("%s exposes the field %q", typ.Name(), name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The two request DTOs have no verification field at all, not even the
|
||||
// read-only ones of the response.
|
||||
for _, dto := range []any{api.OrganizationCreate{}, api.OrganizationUpdate{}} {
|
||||
assertNoJSONFields(t, dto, []string{"verification", "verification_level", "candidate_card", "id", "version", "created_at", "updated_at"})
|
||||
}
|
||||
// The profile fields of a request are the whole editable surface.
|
||||
for _, profile := range []struct {
|
||||
dto any
|
||||
want []string
|
||||
}{
|
||||
{api.OrganizationCreate{}, []string{"name", "description", "sphere", "contacts", "representatives"}},
|
||||
{api.OrganizationUpdate{}, []string{"expected_version", "name", "description", "sphere", "contacts", "representatives"}},
|
||||
} {
|
||||
typ, want := reflect.TypeOf(profile.dto), profile.want
|
||||
got := make([]string, 0, typ.NumField())
|
||||
for i := range typ.NumField() {
|
||||
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
|
||||
got = append(got, name)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Errorf("%s fields = %v, want exactly %v", typ.Name(), got, want)
|
||||
}
|
||||
}
|
||||
// The candidate's card holds neither a member, a role, nor the ground
|
||||
// of the verification.
|
||||
assertNoJSONFields(t, api.CandidateOrganizationCard{}, []string{"role", "membership", "members", "verification", "basis", "version", "created_at", "updated_at", "user_id"})
|
||||
// The caller's own membership is the only place of a role, and it names
|
||||
// no account.
|
||||
assertNoJSONFields(t, api.OrganizationMembership{}, []string{"user_id", "account_id", "email"})
|
||||
// The list takes only the page, so no parameter names another account.
|
||||
params := reflect.TypeFor[api.ListMyOrganizationsParams]()
|
||||
names := make([]string, 0, params.NumField())
|
||||
for i := range params.NumField() {
|
||||
names = append(names, params.Field(i).Name)
|
||||
}
|
||||
if got := strings.Join(names, ","); got != "Limit,Cursor" {
|
||||
t.Fatalf("ListMyOrganizationsParams fields = %s, want only the page", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An update separates an absent list (unchanged) from an empty one (replaced
|
||||
// by an empty list) by nil, and null is not a list or an object.
|
||||
func TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
|
||||
var empty api.OrganizationUpdate
|
||||
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"representatives":[]}`)); err != nil {
|
||||
t.Fatalf("decode an empty list: %v", err)
|
||||
}
|
||||
if empty.Representatives == nil || len(empty.Representatives) != 0 {
|
||||
t.Fatalf("representatives = %#v, want a non-nil empty slice", empty.Representatives)
|
||||
}
|
||||
|
||||
var absent api.OrganizationUpdate
|
||||
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
|
||||
t.Fatalf("decode an absent list: %v", err)
|
||||
}
|
||||
if absent.Representatives != nil || absent.Name.IsSet() || absent.Contacts.IsSet() || absent.Description.IsSet() || absent.Sphere.IsSet() {
|
||||
t.Fatal("absent fields are set, want unset")
|
||||
}
|
||||
|
||||
var cleared api.OrganizationUpdate
|
||||
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"description":null,"sphere":"Платежи"}`)); err != nil {
|
||||
t.Fatalf("decode a null description: %v", err)
|
||||
}
|
||||
if !cleared.Description.IsSet() || !cleared.Description.IsNull() || !cleared.Sphere.IsSet() || cleared.Sphere.IsNull() {
|
||||
t.Fatal("description sent as null is not a set null, or the sphere is not a value")
|
||||
}
|
||||
|
||||
for _, body := range []string{
|
||||
`{"expected_version":1,"representatives":null}`,
|
||||
`{"expected_version":1,"name":null}`,
|
||||
`{"expected_version":1,"contacts":null}`,
|
||||
} {
|
||||
var null api.OrganizationUpdate
|
||||
if err := null.UnmarshalJSON([]byte(body)); err == nil {
|
||||
t.Fatalf("decode %s succeeded, want an error", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The representatives of the candidate card are optional and nullable: absent
|
||||
// or null means that they are not published.
|
||||
func TestCandidateOrganizationCardRepresentativesAreOptional(t *testing.T) {
|
||||
const base = `"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО Пример","description":null,"sphere":null,"contacts":` + emptyOrganizationContacts + `,"verification_level":"e0"`
|
||||
for name, body := range map[string]string{
|
||||
"absent": "{" + base + "}",
|
||||
"null": "{" + base + `,"representatives":null}`,
|
||||
"empty": "{" + base + `,"representatives":[]}`,
|
||||
} {
|
||||
var card api.CandidateOrganizationCard
|
||||
if err := card.UnmarshalJSON([]byte(body)); err != nil {
|
||||
t.Fatalf("decode a card with %s representatives: %v", name, err)
|
||||
}
|
||||
if err := card.Validate(); err != nil {
|
||||
t.Fatalf("validate a card with %s representatives: %v", name, err)
|
||||
}
|
||||
}
|
||||
var withoutContacts api.CandidateOrganizationCard
|
||||
if err := withoutContacts.UnmarshalJSON([]byte(`{"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО","description":null,"sphere":null,"verification_level":"e0"}`)); err == nil {
|
||||
t.Fatal("decode a card without contacts succeeded, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
// The documented examples are valid values of the generated types, and the
|
||||
// organizations they show never claim a level above e0 on their own.
|
||||
func TestOrganizationExamplesAreValidResponsesAndNeverRaiseTheLevel(t *testing.T) {
|
||||
for _, name := range []string{"OrganizationNameOnly", "OrganizationCompleteCard"} {
|
||||
var organization api.Organization
|
||||
if err := organization.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
|
||||
t.Fatalf("decode the %s example: %v", name, err)
|
||||
}
|
||||
if err := organization.Validate(); err != nil {
|
||||
t.Fatalf("validate the %s example: %v", name, err)
|
||||
}
|
||||
if organization.Verification.Level != api.OrganizationVerificationLevelE0 || organization.Verification.Basis != api.OrganizationVerificationBasisConfirmedEmail ||
|
||||
organization.CandidateCard.VerificationLevel != api.OrganizationVerificationLevelE0 {
|
||||
t.Fatalf("%s example verification = %+v, want e0 on the confirmed email", name, organization.Verification)
|
||||
}
|
||||
if organization.CandidateCard.ID != organization.ID || organization.CandidateCard.Name != organization.Name {
|
||||
t.Fatalf("%s example card does not repeat the profile", name)
|
||||
}
|
||||
}
|
||||
var page api.MyOrganizationList
|
||||
if err := page.UnmarshalJSON(supportCaseExample(t, "MyOrganizationListPage")); err != nil {
|
||||
t.Fatalf("decode the MyOrganizationListPage example: %v", err)
|
||||
}
|
||||
if err := page.Validate(); err != nil {
|
||||
t.Fatalf("validate the MyOrganizationListPage example: %v", err)
|
||||
}
|
||||
for _, item := range page.Items {
|
||||
if item.Membership.State != api.MembershipStateActive || item.Membership.OrganizationID != item.Organization.ID {
|
||||
t.Fatalf("listed item %+v, want an active membership of the listed organization", item)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"OrganizationCreateNameOnly", "OrganizationCreateCompleteCard"} {
|
||||
var create api.OrganizationCreate
|
||||
if err := create.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
|
||||
t.Fatalf("decode the %s example: %v", name, err)
|
||||
}
|
||||
if err := create.Validate(); err != nil {
|
||||
t.Fatalf("validate the %s example: %v", name, err)
|
||||
}
|
||||
}
|
||||
var update api.OrganizationUpdate
|
||||
if err := update.UnmarshalJSON(supportCaseExample(t, "OrganizationUpdateCompleteCard")); err != nil {
|
||||
t.Fatalf("decode the OrganizationUpdateCompleteCard example: %v", err)
|
||||
}
|
||||
if err := update.Validate(); err != nil {
|
||||
t.Fatalf("validate the OrganizationUpdateCompleteCard example: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The contract enums list every level, basis, role, and state of the PRD now,
|
||||
// so adding one later is not a contract change. At the contract level, the
|
||||
// profile bodies are closed objects without a role or a level, and no
|
||||
// operation sets the verification level or a role.
|
||||
func TestOrganizationContractFollowsThePRD(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
for name, want := range map[string][]string{
|
||||
"OrganizationVerificationLevel": {"e0", "e1", "e2", "e3"},
|
||||
"OrganizationVerificationBasis": {"confirmed_email", "corporate_domain", "requisites_and_authority", "manual_review", "partner_status"},
|
||||
"OrganizationRole": {"owner", "recruiter", "hiring_manager", "technical_expert"},
|
||||
"MembershipState": {"active", "suspended", "removed", "left"},
|
||||
} {
|
||||
if got := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})); !slices.Equal(got, want) {
|
||||
t.Errorf("%s = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The requests are closed objects whose properties are the profile.
|
||||
for name, want := range map[string][]string{
|
||||
"OrganizationCreate": {"name", "description", "sphere", "contacts", "representatives"},
|
||||
"OrganizationUpdate": {"expected_version", "name", "description", "sphere", "contacts", "representatives"},
|
||||
} {
|
||||
schema := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
|
||||
if schema.AdditionalProperties == nil || schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
|
||||
t.Errorf("%s accepts unknown fields", name)
|
||||
}
|
||||
got := make([]string, 0, len(schema.Properties))
|
||||
for _, property := range schema.Properties {
|
||||
got = append(got, property.Name)
|
||||
}
|
||||
slices.Sort(got)
|
||||
sorted := slices.Clone(want)
|
||||
slices.Sort(sorted)
|
||||
if !slices.Equal(got, sorted) {
|
||||
t.Errorf("%s properties = %v, want %v", name, got, sorted)
|
||||
}
|
||||
}
|
||||
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationUpdate"})
|
||||
if !slices.Contains(update.Required, "expected_version") {
|
||||
t.Error("OrganizationUpdate does not require expected_version")
|
||||
}
|
||||
create := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationCreate"})
|
||||
if !slices.Equal(create.Required, []string{"name"}) {
|
||||
t.Errorf("OrganizationCreate required = %v, want only the name", create.Required)
|
||||
}
|
||||
|
||||
// Writing needs the CSRF token, and creating needs an Idempotency-Key.
|
||||
for _, id := range []string{"CreateOrganization", "UpdateOrganization"} {
|
||||
operation := operationByID(t, spec, id)
|
||||
if len(operation.Security) != 1 {
|
||||
t.Fatalf("%s security = %v, want one requirement", id, operation.Security)
|
||||
}
|
||||
if _, ok := operation.Security[0][sessionCSRFScheme]; !ok {
|
||||
t.Errorf("%s does not require the CSRF token", id)
|
||||
}
|
||||
}
|
||||
if !slices.ContainsFunc(operationByID(t, spec, "CreateOrganization").Parameters, func(parameter *ogen.Parameter) bool {
|
||||
return parameter.Ref == "#/components/parameters/IdempotencyKey"
|
||||
}) {
|
||||
t.Error("CreateOrganization does not require an Idempotency-Key")
|
||||
}
|
||||
if _, ok := operationByID(t, spec, "UpdateOrganization").Responses["412"]; !ok {
|
||||
t.Error("UpdateOrganization does not declare 412")
|
||||
}
|
||||
|
||||
// Nothing in the organization paths sets a verification level or a role.
|
||||
for path, item := range spec.Paths {
|
||||
if !strings.HasPrefix(path, "/api/v1/organizations") && path != myOrganizationsPath {
|
||||
continue
|
||||
}
|
||||
for _, operation := range []*ogen.Operation{item.Get, item.Post, item.Put, item.Patch, item.Delete} {
|
||||
if operation == nil {
|
||||
continue
|
||||
}
|
||||
id := strings.ToLower(operation.OperationID)
|
||||
if strings.Contains(id, "verification") || strings.Contains(id, "verify") || strings.Contains(id, "role") || strings.Contains(id, "promote") {
|
||||
t.Errorf("%s %s sets a level or a role", path, operation.OperationID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// organizationConstraintErrors maps the organization constraints whose
|
||||
// violation is a caller-visible outcome to port sentinels by SQLSTATE and
|
||||
// constraint name, never by text.
|
||||
var organizationConstraintErrors = map[constraintViolation]error{
|
||||
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
|
||||
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
}
|
||||
|
||||
// mapOrganizationError turns a known organization constraint violation into
|
||||
// its port sentinel and keeps the constraint name. Any other PostgreSQL error
|
||||
// is replaced by its SQLSTATE and constraint name, because its detail quotes
|
||||
// the failing row, which holds names of representatives. Deadlocks and
|
||||
// serialization failures also match ErrTransactionConflict. A connection
|
||||
// error loses the pgx prefix that names the database user and database.
|
||||
func mapOrganizationError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
if sentinel, ok := organizationConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
|
||||
return fmt.Errorf("postgres.mapOrganizationError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
|
||||
}
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
|
||||
var _ outbound.OrganizationRepositories = (*UnitOfWork)(nil)
|
||||
|
||||
func (unit *UnitOfWork) Organizations() outbound.OrganizationRepository {
|
||||
return organizationRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) Memberships() outbound.MembershipRepository {
|
||||
return membershipRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type organizationRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.OrganizationRepository = organizationRepository{}
|
||||
|
||||
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
|
||||
const location = "organizationRepository.CreateWithOwner"
|
||||
switch {
|
||||
case organization.IsZero():
|
||||
return fmt.Errorf("%s - organization was not built by domain.NewOrganization: %w", location, domain.ErrInvalidOrganization)
|
||||
case owner.IsZero():
|
||||
return fmt.Errorf("%s - owner was not built by domain.NewOwnerMembership: %w", location, domain.ErrInvalidMembership)
|
||||
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
|
||||
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
|
||||
}
|
||||
profile := organization.Profile()
|
||||
contacts := profile.Contacts()
|
||||
verification := organization.Verification()
|
||||
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
|
||||
ID: pgUUID(organization.ID()),
|
||||
Name: profile.Name(),
|
||||
Description: pgOptionalText(profile.Description()),
|
||||
Sphere: pgOptionalText(profile.Sphere()),
|
||||
ContactWebsite: pgOptionalText(contacts.Website()),
|
||||
ContactEmail: pgOptionalText(contacts.Email()),
|
||||
ContactPhone: pgOptionalText(contacts.Phone()),
|
||||
ContactTelegram: pgOptionalText(contacts.Telegram()),
|
||||
VerificationLevel: string(verification.Level()),
|
||||
VerificationBasis: string(verification.Basis()),
|
||||
VerificationChangedAt: pgTime(verification.ChangedAt()),
|
||||
Version: organization.Version(),
|
||||
CreatedAt: pgTime(organization.CreatedAt()),
|
||||
UpdatedAt: pgTime(organization.UpdatedAt()),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
|
||||
return fmt.Errorf("%s - insert representatives: %w", location, err)
|
||||
}
|
||||
if err := insertMembership(ctx, repository.queries, owner); err != nil {
|
||||
return fmt.Errorf("%s - insert owner membership: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) insertRepresentatives(
|
||||
ctx context.Context,
|
||||
organizationID uuid.UUID,
|
||||
representatives []domain.OrganizationRepresentative,
|
||||
) error {
|
||||
for index, representative := range representatives {
|
||||
err := repository.queries.InsertOrganizationRepresentative(ctx, sqlc.InsertOrganizationRepresentativeParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
Ordinal: int16(index),
|
||||
Name: representative.Name(),
|
||||
JobTitle: representative.JobTitle(),
|
||||
})
|
||||
if err != nil {
|
||||
return mapOrganizationError(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) GetForMember(
|
||||
ctx context.Context,
|
||||
organizationID, userID uuid.UUID,
|
||||
) (domain.Organization, domain.Membership, error) {
|
||||
const location = "organizationRepository.GetForMember"
|
||||
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
UserID: pgUUID(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - select organization: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
|
||||
}
|
||||
representatives, err := decodeRepresentatives(row.Representatives)
|
||||
if err != nil {
|
||||
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - decode representatives: %w", location, err)
|
||||
}
|
||||
organization, err := organizationFromColumns(organizationColumns{
|
||||
ID: row.ID, Name: row.Name, Description: row.Description, Sphere: row.Sphere,
|
||||
ContactWebsite: row.ContactWebsite, ContactEmail: row.ContactEmail,
|
||||
ContactPhone: row.ContactPhone, ContactTelegram: row.ContactTelegram,
|
||||
VerificationLevel: row.VerificationLevel, VerificationBasis: row.VerificationBasis,
|
||||
VerificationChangedAt: row.VerificationChangedAt, Version: row.Version,
|
||||
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
||||
}, representatives)
|
||||
if err != nil {
|
||||
return domain.Organization{}, domain.Membership{}, err
|
||||
}
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: optionalUUID(row.MembershipID),
|
||||
OrganizationID: organizationID,
|
||||
UserID: userID,
|
||||
Role: row.MembershipRole,
|
||||
State: row.MembershipState,
|
||||
CreatedAt: row.MembershipCreatedAt.Time,
|
||||
UpdatedAt: row.MembershipUpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
|
||||
}
|
||||
return organization, membership, nil
|
||||
}
|
||||
|
||||
// representativeJSON is one element of the representatives column that
|
||||
// GetOrganizationForMember aggregates in the same statement as the
|
||||
// organization, so the profile and the list come from one snapshot.
|
||||
type representativeJSON struct {
|
||||
Name string `json:"name"`
|
||||
JobTitle string `json:"job_title"`
|
||||
}
|
||||
|
||||
func decodeRepresentatives(column string) ([]domain.StoredRepresentative, error) {
|
||||
var decoded []representativeJSON
|
||||
if err := json.Unmarshal([]byte(column), &decoded); err != nil {
|
||||
// The error of the decoder can quote the document, which holds names.
|
||||
return nil, errors.New("postgres.decodeRepresentatives - the representatives column is not a list of name and job title")
|
||||
}
|
||||
representatives := make([]domain.StoredRepresentative, 0, len(decoded))
|
||||
for _, representative := range decoded {
|
||||
representatives = append(representatives, domain.StoredRepresentative(representative))
|
||||
}
|
||||
return representatives, nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) ListForUser(ctx context.Context, query outbound.OrganizationListQuery) (outbound.OrganizationPage, error) {
|
||||
const location = "organizationRepository.ListForUser"
|
||||
if query.UserID == uuid.Nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidMembership)
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxOrganizationPageSize {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
|
||||
}
|
||||
params := sqlc.ListOrganizationsForUserParams{
|
||||
UserID: pgUUID(query.UserID),
|
||||
// One extra row tells whether another page follows.
|
||||
RowLimit: query.Limit + 1,
|
||||
}
|
||||
if query.After != nil {
|
||||
if err := requireTime(location, query.After.JoinedAt, domain.ErrInvalidMembership); err != nil {
|
||||
return outbound.OrganizationPage{}, err
|
||||
}
|
||||
if query.After.OrganizationID == uuid.Nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - position organization ID must not be nil: %w", location, domain.ErrInvalidMembership)
|
||||
}
|
||||
params.AfterJoinedAt = pgTime(query.After.JoinedAt)
|
||||
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
|
||||
}
|
||||
rows, err := repository.queries.ListOrganizationsForUser(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - select organizations: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
page := outbound.OrganizationPage{HasMore: len(rows) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
page.Items = make([]outbound.MemberOrganization, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
summary, err := domain.RestoreOrganizationSummary(optionalUUID(row.ID), row.Name, row.VerificationLevel)
|
||||
if err != nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore organization: %w", location, err)
|
||||
}
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: optionalUUID(row.MembershipID),
|
||||
OrganizationID: summary.ID(),
|
||||
UserID: query.UserID,
|
||||
Role: row.MembershipRole,
|
||||
State: row.MembershipState,
|
||||
CreatedAt: row.MembershipCreatedAt.Time,
|
||||
UpdatedAt: row.MembershipUpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore membership: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, outbound.MemberOrganization{Organization: summary, Membership: membership})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) UpdateProfile(
|
||||
ctx context.Context,
|
||||
actorID uuid.UUID,
|
||||
organization domain.Organization,
|
||||
) (domain.Organization, error) {
|
||||
const location = "organizationRepository.UpdateProfile"
|
||||
if organization.IsZero() || actorID == uuid.Nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - organization and actor must be set: %w", location, domain.ErrInvalidOrganization)
|
||||
}
|
||||
// The generated parameter structs of this repository hold representative
|
||||
// names and contacts: never log them.
|
||||
profile := organization.Profile()
|
||||
contacts := profile.Contacts()
|
||||
row, err := repository.queries.UpdateOrganizationProfile(ctx, sqlc.UpdateOrganizationProfileParams{
|
||||
Name: profile.Name(),
|
||||
Description: pgOptionalText(profile.Description()),
|
||||
Sphere: pgOptionalText(profile.Sphere()),
|
||||
ContactWebsite: pgOptionalText(contacts.Website()),
|
||||
ContactEmail: pgOptionalText(contacts.Email()),
|
||||
ContactPhone: pgOptionalText(contacts.Phone()),
|
||||
ContactTelegram: pgOptionalText(contacts.Telegram()),
|
||||
UpdatedAt: pgTime(organization.UpdatedAt()),
|
||||
ID: pgUUID(organization.ID()),
|
||||
ExpectedVersion: organization.Version(),
|
||||
ActorID: pgUUID(actorID),
|
||||
ManagerRoles: managerRoleNames(),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, repository.explainRejectedUpdate(ctx, actorID, organization))
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
// The row lock of the update holds until the transaction ends, so no
|
||||
// other writer replaces the list between these statements.
|
||||
if err := repository.queries.DeleteOrganizationRepresentatives(ctx, row.ID); err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - delete representatives: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - insert representatives: %w", location, err)
|
||||
}
|
||||
stored := make([]domain.StoredRepresentative, 0, len(profile.Representatives()))
|
||||
for _, representative := range profile.Representatives() {
|
||||
stored = append(stored, domain.StoredRepresentative{Name: representative.Name(), JobTitle: representative.JobTitle()})
|
||||
}
|
||||
return organizationFromColumns(organizationColumns(row), stored)
|
||||
}
|
||||
|
||||
// explainRejectedUpdate tells why the update matched no row: an unknown
|
||||
// organization or an actor without an active membership, a membership whose
|
||||
// role cannot manage, or a stale version, in that order.
|
||||
func (repository organizationRepository) explainRejectedUpdate(
|
||||
ctx context.Context,
|
||||
actorID uuid.UUID,
|
||||
organization domain.Organization,
|
||||
) error {
|
||||
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
|
||||
OrganizationID: pgUUID(organization.ID()),
|
||||
UserID: pgUUID(actorID),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return outbound.ErrOrganizationNotFound
|
||||
case err != nil:
|
||||
return mapOrganizationError(err)
|
||||
}
|
||||
role, err := domain.ParseOrganizationRole(row.MembershipRole)
|
||||
switch {
|
||||
case err != nil:
|
||||
return fmt.Errorf("postgres.explainRejectedUpdate - validate role: %w", err)
|
||||
case !role.CanManageOrganization():
|
||||
return outbound.ErrOrganizationManagerRequired
|
||||
default:
|
||||
return outbound.ErrOrganizationVersionConflict
|
||||
}
|
||||
}
|
||||
|
||||
func managerRoleNames() []string {
|
||||
roles := domain.ManagerRoles()
|
||||
names := make([]string, 0, len(roles))
|
||||
for _, role := range roles {
|
||||
names = append(names, string(role))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// organizationColumns has the columns of an organization row that every
|
||||
// organization query returns. The generated row of UpdateOrganizationProfile
|
||||
// converts to it.
|
||||
type organizationColumns struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func organizationFromColumns(columns organizationColumns, representatives []domain.StoredRepresentative) (domain.Organization, error) {
|
||||
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: optionalUUID(columns.ID),
|
||||
Name: columns.Name,
|
||||
Description: columns.Description.String,
|
||||
Sphere: columns.Sphere.String,
|
||||
Website: columns.ContactWebsite.String,
|
||||
Email: columns.ContactEmail.String,
|
||||
Phone: columns.ContactPhone.String,
|
||||
Telegram: columns.ContactTelegram.String,
|
||||
Representatives: representatives,
|
||||
VerificationLevel: columns.VerificationLevel,
|
||||
VerificationBasis: columns.VerificationBasis,
|
||||
VerificationChangedAt: columns.VerificationChangedAt.Time,
|
||||
Version: columns.Version,
|
||||
CreatedAt: columns.CreatedAt.Time,
|
||||
UpdatedAt: columns.UpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("postgres.organizationFromColumns - restore organization: %w", err)
|
||||
}
|
||||
return organization, nil
|
||||
}
|
||||
|
||||
type membershipRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.MembershipRepository = membershipRepository{}
|
||||
|
||||
func (repository membershipRepository) Insert(ctx context.Context, membership domain.Membership) error {
|
||||
if membership.IsZero() {
|
||||
return fmt.Errorf("membershipRepository.Insert - membership was not built by domain.NewMembership: %w", domain.ErrInvalidMembership)
|
||||
}
|
||||
if err := insertMembership(ctx, repository.queries, membership); err != nil {
|
||||
return fmt.Errorf("membershipRepository.Insert - insert membership: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertMembership(ctx context.Context, queries *sqlc.Queries, membership domain.Membership) error {
|
||||
err := queries.InsertMembership(ctx, sqlc.InsertMembershipParams{
|
||||
ID: pgUUID(membership.ID()),
|
||||
OrganizationID: pgUUID(membership.OrganizationID()),
|
||||
UserID: pgUUID(membership.UserID()),
|
||||
Role: string(membership.Role()),
|
||||
State: string(membership.State()),
|
||||
CreatedAt: pgTime(membership.CreatedAt()),
|
||||
UpdatedAt: pgTime(membership.UpdatedAt()),
|
||||
})
|
||||
if err != nil {
|
||||
return mapOrganizationError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository membershipRepository) Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
const location = "membershipRepository.Get"
|
||||
row, err := repository.queries.GetMembership(ctx, sqlc.GetMembershipParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
UserID: pgUUID(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - select membership: %w", location, mapOrganizationNoRows(err, outbound.ErrMembershipNotFound))
|
||||
}
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: optionalUUID(row.ID),
|
||||
OrganizationID: optionalUUID(row.OrganizationID),
|
||||
UserID: optionalUUID(row.UserID),
|
||||
Role: row.Role,
|
||||
State: row.State,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
UpdatedAt: row.UpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
func mapOrganizationNoRows(err, sentinel error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return sentinel
|
||||
}
|
||||
return mapOrganizationError(err)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// organizationDetailMarker stands for a row value that a PostgreSQL detail
|
||||
// can quote, such as the name of a representative.
|
||||
const organizationDetailMarker = "Failing row contains (Анна Тестова, Руководитель)"
|
||||
|
||||
func TestMapOrganizationErrorRecognizesOrganizationConstraints(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
code string
|
||||
constraint string
|
||||
want error
|
||||
}{
|
||||
{code: uniqueViolationCode, constraint: "memberships_user_id_organization_id_key", want: outbound.ErrMembershipExists},
|
||||
{code: foreignKeyViolationCode, constraint: "memberships_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
|
||||
{code: foreignKeyViolationCode, constraint: "memberships_user_id_fkey", want: outbound.ErrUserNotFound},
|
||||
{code: foreignKeyViolationCode, constraint: "organization_representatives_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
|
||||
} {
|
||||
err := mapOrganizationError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: organizationDetailMarker})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("mapOrganizationError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "Failing row") {
|
||||
t.Fatalf("mapOrganizationError(%s) = %v, want the constraint name and no detail", test.constraint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapOrganizationErrorDropsDetailOfOtherErrors(t *testing.T) {
|
||||
// A CHECK violation that the domain should have prevented keeps only the
|
||||
// SQLSTATE and the constraint, never the failing row with its names.
|
||||
err := mapOrganizationError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "organization_representatives_name_format", Detail: organizationDetailMarker})
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
|
||||
t.Fatalf("mapOrganizationError() = %v, want SQLSTATE %s", err, checkViolationCode)
|
||||
}
|
||||
if strings.Contains(err.Error(), "Анна") || strings.Contains(err.Error(), "Failing row") {
|
||||
t.Fatalf("mapOrganizationError() = %v, want no row values", err)
|
||||
}
|
||||
if err := mapOrganizationError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("mapOrganizationError(deadlock) = %v, want ErrTransactionConflict", err)
|
||||
}
|
||||
if err := mapOrganizationError(context.Canceled); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("mapOrganizationError(context.Canceled) = %v, want the original error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationRepositoriesRejectInvalidInputBeforeQuerying(t *testing.T) {
|
||||
// A repository without queries proves that no statement runs.
|
||||
organizations := organizationRepository{}
|
||||
memberships := membershipRepository{}
|
||||
ctx := t.Context()
|
||||
if err := organizations.CreateWithOwner(ctx, domain.Organization{}, domain.Membership{}); !errors.Is(err, domain.ErrInvalidOrganization) {
|
||||
t.Fatalf("CreateWithOwner(zero organization) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
if err := memberships.Insert(ctx, domain.Membership{}); !errors.Is(err, domain.ErrInvalidMembership) {
|
||||
t.Fatalf("Insert(zero membership) error = %v, want ErrInvalidMembership", err)
|
||||
}
|
||||
if _, err := organizations.UpdateProfile(ctx, uuid.New(), domain.Organization{}); !errors.Is(err, domain.ErrInvalidOrganization) {
|
||||
t.Fatalf("UpdateProfile(zero organization) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
if _, err := organizations.ListForUser(ctx, outbound.OrganizationListQuery{}); !errors.Is(err, domain.ErrInvalidMembership) {
|
||||
t.Fatalf("ListForUser(zero query) error = %v, want ErrInvalidMembership", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
|
||||
if got := managerRoleNames(); len(got) != 1 || got[0] != string(domain.OrganizationRoleOwner) {
|
||||
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,40 @@ type MailRequest struct {
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Membership struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Role string
|
||||
State string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Organization struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type OrganizationRepresentative struct {
|
||||
OrganizationID pgtype.UUID
|
||||
Ordinal int16
|
||||
Name string
|
||||
JobTitle string
|
||||
}
|
||||
|
||||
type OutboxEvent struct {
|
||||
Position pgtype.Int8
|
||||
EventID pgtype.UUID
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: organizations.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteOrganizationRepresentatives = `-- name: DeleteOrganizationRepresentatives :exec
|
||||
DELETE FROM organization_representatives
|
||||
WHERE organization_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deleteOrganizationRepresentatives, organizationID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getMembership = `-- name: GetMembership :one
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
user_id,
|
||||
role,
|
||||
state,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM memberships
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND user_id = $2
|
||||
`
|
||||
|
||||
type GetMembershipParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
// Reads the membership of one account in one organization, in any state.
|
||||
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
|
||||
row := q.db.QueryRow(ctx, getMembership, arg.OrganizationID, arg.UserID)
|
||||
var i Membership
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrganizationID,
|
||||
&i.UserID,
|
||||
&i.Role,
|
||||
&i.State,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
|
||||
SELECT
|
||||
organization.id,
|
||||
organization.name,
|
||||
organization.description,
|
||||
organization.sphere,
|
||||
organization.contact_website,
|
||||
organization.contact_email,
|
||||
organization.contact_phone,
|
||||
organization.contact_telegram,
|
||||
organization.verification_level,
|
||||
organization.verification_basis,
|
||||
organization.verification_changed_at,
|
||||
organization.version,
|
||||
organization.created_at,
|
||||
organization.updated_at,
|
||||
coalesce((
|
||||
SELECT
|
||||
jsonb_agg(
|
||||
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
|
||||
ORDER BY representative.ordinal
|
||||
)
|
||||
FROM organization_representatives AS representative
|
||||
WHERE representative.organization_id = organization.id
|
||||
), '[]'::jsonb)::text AS representatives,
|
||||
membership.id AS membership_id,
|
||||
membership.role AS membership_role,
|
||||
membership.state AS membership_state,
|
||||
membership.created_at AS membership_created_at,
|
||||
membership.updated_at AS membership_updated_at
|
||||
FROM organizations AS organization
|
||||
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
|
||||
WHERE
|
||||
organization.id = $1
|
||||
AND membership.user_id = $2
|
||||
AND membership.state = 'active'
|
||||
`
|
||||
|
||||
type GetOrganizationForMemberParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
type GetOrganizationForMemberRow struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
Representatives string
|
||||
MembershipID pgtype.UUID
|
||||
MembershipRole string
|
||||
MembershipState string
|
||||
MembershipCreatedAt pgtype.Timestamptz
|
||||
MembershipUpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Reads an organization together with the membership of one account in it
|
||||
// and its representatives in list order, as one statement, so the profile and
|
||||
// the list come from one snapshot. Only an active membership matches, so an
|
||||
// unknown organization, an account that is no member, and a suspended,
|
||||
// removed, or left member all return no row and cannot be told apart.
|
||||
func (q *Queries) GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error) {
|
||||
row := q.db.QueryRow(ctx, getOrganizationForMember, arg.OrganizationID, arg.UserID)
|
||||
var i GetOrganizationForMemberRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.Description,
|
||||
&i.Sphere,
|
||||
&i.ContactWebsite,
|
||||
&i.ContactEmail,
|
||||
&i.ContactPhone,
|
||||
&i.ContactTelegram,
|
||||
&i.VerificationLevel,
|
||||
&i.VerificationBasis,
|
||||
&i.VerificationChangedAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Representatives,
|
||||
&i.MembershipID,
|
||||
&i.MembershipRole,
|
||||
&i.MembershipState,
|
||||
&i.MembershipCreatedAt,
|
||||
&i.MembershipUpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMembership = `-- name: InsertMembership :exec
|
||||
INSERT INTO memberships (
|
||||
id,
|
||||
organization_id,
|
||||
user_id,
|
||||
role,
|
||||
state,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertMembershipParams struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Role string
|
||||
State string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMembership(ctx context.Context, arg InsertMembershipParams) error {
|
||||
_, err := q.db.Exec(ctx, insertMembership,
|
||||
arg.ID,
|
||||
arg.OrganizationID,
|
||||
arg.UserID,
|
||||
arg.Role,
|
||||
arg.State,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertOrganization = `-- name: InsertOrganization :exec
|
||||
INSERT INTO organizations (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
sphere,
|
||||
contact_website,
|
||||
contact_email,
|
||||
contact_phone,
|
||||
contact_telegram,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11,
|
||||
$12,
|
||||
$13,
|
||||
$14
|
||||
)
|
||||
`
|
||||
|
||||
type InsertOrganizationParams struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOrganization,
|
||||
arg.ID,
|
||||
arg.Name,
|
||||
arg.Description,
|
||||
arg.Sphere,
|
||||
arg.ContactWebsite,
|
||||
arg.ContactEmail,
|
||||
arg.ContactPhone,
|
||||
arg.ContactTelegram,
|
||||
arg.VerificationLevel,
|
||||
arg.VerificationBasis,
|
||||
arg.VerificationChangedAt,
|
||||
arg.Version,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertOrganizationRepresentative = `-- name: InsertOrganizationRepresentative :exec
|
||||
INSERT INTO organization_representatives (
|
||||
organization_id,
|
||||
ordinal,
|
||||
name,
|
||||
job_title
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4
|
||||
)
|
||||
`
|
||||
|
||||
type InsertOrganizationRepresentativeParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
Ordinal int16
|
||||
Name string
|
||||
JobTitle string
|
||||
}
|
||||
|
||||
// Stores one representative at its position in the list. The adapter calls it
|
||||
// once per representative after it deleted the previous list, in the same
|
||||
// transaction.
|
||||
func (q *Queries) InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOrganizationRepresentative,
|
||||
arg.OrganizationID,
|
||||
arg.Ordinal,
|
||||
arg.Name,
|
||||
arg.JobTitle,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listOrganizationsForUser = `-- name: ListOrganizationsForUser :many
|
||||
SELECT
|
||||
organization.id,
|
||||
organization.name,
|
||||
organization.verification_level,
|
||||
membership.id AS membership_id,
|
||||
membership.role AS membership_role,
|
||||
membership.state AS membership_state,
|
||||
membership.created_at AS membership_created_at,
|
||||
membership.updated_at AS membership_updated_at
|
||||
FROM memberships AS membership
|
||||
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
|
||||
WHERE
|
||||
membership.user_id = $1
|
||||
AND membership.state = 'active'
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (membership.created_at, membership.organization_id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY membership.created_at DESC, membership.organization_id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListOrganizationsForUserParams struct {
|
||||
UserID pgtype.UUID
|
||||
AfterJoinedAt pgtype.Timestamptz
|
||||
AfterOrganizationID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListOrganizationsForUserRow struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
VerificationLevel string
|
||||
MembershipID pgtype.UUID
|
||||
MembershipRole string
|
||||
MembershipState string
|
||||
MembershipCreatedAt pgtype.Timestamptz
|
||||
MembershipUpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
// creation time, organization ID) position of the last item of the
|
||||
// previous page. Only the active memberships of the given account match.
|
||||
func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOrganizationsForUser,
|
||||
arg.UserID,
|
||||
arg.AfterJoinedAt,
|
||||
arg.AfterOrganizationID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListOrganizationsForUserRow
|
||||
for rows.Next() {
|
||||
var i ListOrganizationsForUserRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.VerificationLevel,
|
||||
&i.MembershipID,
|
||||
&i.MembershipRole,
|
||||
&i.MembershipState,
|
||||
&i.MembershipCreatedAt,
|
||||
&i.MembershipUpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
|
||||
WITH target AS (
|
||||
SELECT id FROM organizations
|
||||
WHERE
|
||||
id = $9
|
||||
AND version = $10
|
||||
FOR UPDATE
|
||||
),
|
||||
|
||||
actor AS (
|
||||
SELECT memberships.id FROM memberships
|
||||
INNER JOIN target ON memberships.organization_id = target.id
|
||||
WHERE
|
||||
memberships.user_id = $11
|
||||
AND memberships.state = 'active'
|
||||
AND memberships.role = any($12::text [])
|
||||
FOR SHARE OF memberships
|
||||
)
|
||||
|
||||
UPDATE organizations
|
||||
SET
|
||||
name = $1,
|
||||
description = $2,
|
||||
sphere = $3,
|
||||
contact_website = $4,
|
||||
contact_email = $5,
|
||||
contact_phone = $6,
|
||||
contact_telegram = $7,
|
||||
updated_at = $8,
|
||||
version = organizations.version + 1
|
||||
FROM actor
|
||||
WHERE
|
||||
organizations.id = $9
|
||||
AND organizations.version = $10
|
||||
RETURNING
|
||||
organizations.id,
|
||||
organizations.name,
|
||||
organizations.description,
|
||||
organizations.sphere,
|
||||
organizations.contact_website,
|
||||
organizations.contact_email,
|
||||
organizations.contact_phone,
|
||||
organizations.contact_telegram,
|
||||
organizations.verification_level,
|
||||
organizations.verification_basis,
|
||||
organizations.verification_changed_at,
|
||||
organizations.version,
|
||||
organizations.created_at,
|
||||
organizations.updated_at
|
||||
`
|
||||
|
||||
type UpdateOrganizationProfileParams struct {
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
ActorID pgtype.UUID
|
||||
ManagerRoles []string
|
||||
}
|
||||
|
||||
// Changes the profile of an organization over the version the caller read
|
||||
// and advances the version in the same statement. It names no verification
|
||||
// column, so a profile update cannot move the trust level. The change
|
||||
// applies only for an account whose active membership has one of the
|
||||
// manager roles, checked in the statement itself so that a membership that
|
||||
// ended after the caller's read still stops the write. The statement locks
|
||||
// the organization row first and then the actor's membership row FOR SHARE,
|
||||
// so a revocation that commits while the statement waits is seen again
|
||||
// (EvalPlanQual) and stops the write; the order organizations, then
|
||||
// memberships, is the lock order of every writer (member management must
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
|
||||
row := q.db.QueryRow(ctx, updateOrganizationProfile,
|
||||
arg.Name,
|
||||
arg.Description,
|
||||
arg.Sphere,
|
||||
arg.ContactWebsite,
|
||||
arg.ContactEmail,
|
||||
arg.ContactPhone,
|
||||
arg.ContactTelegram,
|
||||
arg.UpdatedAt,
|
||||
arg.ID,
|
||||
arg.ExpectedVersion,
|
||||
arg.ActorID,
|
||||
arg.ManagerRoles,
|
||||
)
|
||||
var i Organization
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.Description,
|
||||
&i.Sphere,
|
||||
&i.ContactWebsite,
|
||||
&i.ContactEmail,
|
||||
&i.ContactPhone,
|
||||
&i.ContactTelegram,
|
||||
&i.VerificationLevel,
|
||||
&i.VerificationBasis,
|
||||
&i.VerificationChangedAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -49,6 +49,7 @@ type Querier interface {
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
@@ -112,6 +113,14 @@ type Querier interface {
|
||||
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
|
||||
// Reads the usage of the day and the month window without locking.
|
||||
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
|
||||
// Reads the membership of one account in one organization, in any state.
|
||||
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
|
||||
// Reads an organization together with the membership of one account in it
|
||||
// and its representatives in list order, as one statement, so the profile and
|
||||
// the list come from one snapshot. Only an active membership matches, so an
|
||||
// unknown organization, an account that is no member, and a suspended,
|
||||
// removed, or left member all return no row and cannot be told apart.
|
||||
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
|
||||
// Reads the relay backlog for metrics without locking. Both subqueries use
|
||||
// the partial index on unpublished positions, so the cost follows the backlog
|
||||
// size, not the table size. The age comes from the database clock, the same
|
||||
@@ -153,6 +162,16 @@ type Querier interface {
|
||||
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
|
||||
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
|
||||
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
|
||||
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
|
||||
// Stores one representative at its position in the list. The adapter calls it
|
||||
// once per representative after it deleted the previous list, in the same
|
||||
// transaction.
|
||||
InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error
|
||||
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
|
||||
// Stores a version and returns the stored row with the publication time and
|
||||
// effective time set by the stamp trigger. A taken ID or version number
|
||||
@@ -189,6 +208,11 @@ type Querier interface {
|
||||
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
|
||||
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
// creation time, organization ID) position of the last item of the
|
||||
// previous page. Only the active memberships of the given account match.
|
||||
ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error)
|
||||
// Lists the other accounts of a provider that have usage in a month, so
|
||||
// startup can warn about a renamed EMAIL_ACCOUNT.
|
||||
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
|
||||
@@ -304,6 +328,20 @@ type Querier interface {
|
||||
// the stored version still equals expected_version and returns 0 rows
|
||||
// otherwise. The trigger refuses a provider change after an attempt.
|
||||
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
|
||||
// Changes the profile of an organization over the version the caller read
|
||||
// and advances the version in the same statement. It names no verification
|
||||
// column, so a profile update cannot move the trust level. The change
|
||||
// applies only for an account whose active membership has one of the
|
||||
// manager roles, checked in the statement itself so that a membership that
|
||||
// ended after the caller's read still stops the write. The statement locks
|
||||
// the organization row first and then the actor's membership row FOR SHARE,
|
||||
// so a revocation that commits while the statement waits is seen again
|
||||
// (EvalPlanQual) and stops the write; the order organizations, then
|
||||
// memberships, is the lock order of every writer (member management must
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidMembership reports a membership, role, or state that breaks a
|
||||
// rule, including a stored membership that does not match one.
|
||||
var ErrInvalidMembership = errors.New("invalid membership")
|
||||
|
||||
// OrganizationRole is the role of a member in one organization (PRD 2.2 and
|
||||
// the FR07 matrix). The role belongs to the membership, never to the
|
||||
// organization profile. Values match the OrganizationRole schema of the
|
||||
// public contract.
|
||||
type OrganizationRole string
|
||||
|
||||
const (
|
||||
// OrganizationRoleOwner manages the organization and its members.
|
||||
OrganizationRoleOwner OrganizationRole = "owner"
|
||||
// OrganizationRoleRecruiter leads the selection of candidates.
|
||||
OrganizationRoleRecruiter OrganizationRole = "recruiter"
|
||||
// OrganizationRoleHiringManager acts on the assigned needs.
|
||||
OrganizationRoleHiringManager OrganizationRole = "hiring_manager"
|
||||
// OrganizationRoleTechnicalExpert refines the requirements of the
|
||||
// assigned needs.
|
||||
OrganizationRoleTechnicalExpert OrganizationRole = "technical_expert"
|
||||
)
|
||||
|
||||
// OrganizationRoles lists every role, the owner first.
|
||||
func OrganizationRoles() []OrganizationRole {
|
||||
return []OrganizationRole{
|
||||
OrganizationRoleOwner,
|
||||
OrganizationRoleRecruiter,
|
||||
OrganizationRoleHiringManager,
|
||||
OrganizationRoleTechnicalExpert,
|
||||
}
|
||||
}
|
||||
|
||||
// ParseOrganizationRole accepts a value of the OrganizationRole contract
|
||||
// enum.
|
||||
func ParseOrganizationRole(value string) (OrganizationRole, error) {
|
||||
role := OrganizationRole(value)
|
||||
if !slices.Contains(OrganizationRoles(), role) {
|
||||
return "", fmt.Errorf("domain.ParseOrganizationRole - unknown role: %w", ErrInvalidMembership)
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// CanManageOrganization reports whether the role changes the organization
|
||||
// profile and manages its members. The FR07 matrix gives this to the owner
|
||||
// only. It is the single rule of managing; the rest of the matrix (needs,
|
||||
// invitations, contacts, bids) is applied by the operations it governs, and
|
||||
// no role grants anything through this method alone.
|
||||
func (role OrganizationRole) CanManageOrganization() bool {
|
||||
return role == OrganizationRoleOwner
|
||||
}
|
||||
|
||||
// ManagerRoles lists the roles for which CanManageOrganization is true.
|
||||
func ManagerRoles() []OrganizationRole {
|
||||
managers := make([]OrganizationRole, 0, 1)
|
||||
for _, role := range OrganizationRoles() {
|
||||
if role.CanManageOrganization() {
|
||||
managers = append(managers, role)
|
||||
}
|
||||
}
|
||||
return managers
|
||||
}
|
||||
|
||||
// MembershipState is the state of a membership. Only an active membership
|
||||
// gives access. Values match the MembershipState schema of the public
|
||||
// contract.
|
||||
type MembershipState string
|
||||
|
||||
const (
|
||||
// MembershipStateActive is a member who works in the organization.
|
||||
MembershipStateActive MembershipState = "active"
|
||||
// MembershipStateSuspended is a member whose access is stopped and may be
|
||||
// restored.
|
||||
MembershipStateSuspended MembershipState = "suspended"
|
||||
// MembershipStateRemoved is a membership that the owner or the platform
|
||||
// ended.
|
||||
MembershipStateRemoved MembershipState = "removed"
|
||||
// MembershipStateLeft is a membership that the member ended.
|
||||
MembershipStateLeft MembershipState = "left"
|
||||
)
|
||||
|
||||
// ParseMembershipState accepts a value of the MembershipState contract enum.
|
||||
func ParseMembershipState(value string) (MembershipState, error) {
|
||||
state := MembershipState(value)
|
||||
switch state {
|
||||
case MembershipStateActive, MembershipStateSuspended, MembershipStateRemoved, MembershipStateLeft:
|
||||
return state, nil
|
||||
default:
|
||||
return "", fmt.Errorf("domain.ParseMembershipState - unknown state: %w", ErrInvalidMembership)
|
||||
}
|
||||
}
|
||||
|
||||
// GrantsAccess reports whether a membership in the state gives access to its
|
||||
// organization. Every state but active answers as if the account were no
|
||||
// member.
|
||||
func (state MembershipState) GrantsAccess() bool { return state == MembershipStateActive }
|
||||
|
||||
// MembershipInput describes a new membership.
|
||||
type MembershipInput struct {
|
||||
OrganizationID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Role OrganizationRole
|
||||
// At is the application clock at creation.
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// Membership is the role of one account in one organization. An account has
|
||||
// at most one membership per organization, so storage keeps the pair unique.
|
||||
// Storage reconstructs it from trusted rows with RestoreMembership; new ones
|
||||
// come from NewMembership.
|
||||
type Membership struct {
|
||||
id uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
userID uuid.UUID
|
||||
role OrganizationRole
|
||||
state MembershipState
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
// NewMembership creates an active membership with a time-ordered UUIDv7
|
||||
// identifier. It checks the shape only: whether the account may hold the
|
||||
// role, for example whether it is an employer account, is a rule of the
|
||||
// operation that adds the member.
|
||||
func NewMembership(input MembershipInput) (Membership, error) {
|
||||
const location = "domain.NewMembership"
|
||||
if _, err := ParseOrganizationRole(string(input.Role)); err != nil {
|
||||
return Membership{}, fmt.Errorf("%s - validate role: %w", location, err)
|
||||
}
|
||||
switch {
|
||||
case input.OrganizationID == uuid.Nil:
|
||||
return Membership{}, fmt.Errorf("%s - organization ID must not be nil: %w", location, ErrInvalidMembership)
|
||||
case input.UserID == uuid.Nil:
|
||||
return Membership{}, fmt.Errorf("%s - user ID must not be nil: %w", location, ErrInvalidMembership)
|
||||
case input.At.IsZero():
|
||||
return Membership{}, fmt.Errorf("%s - creation time must be set: %w", location, ErrInvalidMembership)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Membership{}, fmt.Errorf("%s - generate membership ID: %w", location, err)
|
||||
}
|
||||
return Membership{
|
||||
id: id,
|
||||
organizationID: input.OrganizationID,
|
||||
userID: input.UserID,
|
||||
role: input.Role,
|
||||
state: MembershipStateActive,
|
||||
createdAt: input.At,
|
||||
updatedAt: input.At,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewOwnerMembership creates the active owner membership of the account that
|
||||
// creates an organization.
|
||||
func NewOwnerMembership(organizationID, userID uuid.UUID, at time.Time) (Membership, error) {
|
||||
return NewMembership(MembershipInput{OrganizationID: organizationID, UserID: userID, Role: OrganizationRoleOwner, At: at})
|
||||
}
|
||||
|
||||
// StoredMembership carries the columns of a stored membership.
|
||||
type StoredMembership struct {
|
||||
ID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Role string
|
||||
State string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// RestoreMembership validates a stored membership, so a row changed outside
|
||||
// the application fails with ErrInvalidMembership.
|
||||
func RestoreMembership(stored StoredMembership) (Membership, error) {
|
||||
const location = "domain.RestoreMembership"
|
||||
role, err := ParseOrganizationRole(stored.Role)
|
||||
if err != nil {
|
||||
return Membership{}, fmt.Errorf("%s - validate role: %w", location, err)
|
||||
}
|
||||
state, err := ParseMembershipState(stored.State)
|
||||
if err != nil {
|
||||
return Membership{}, fmt.Errorf("%s - validate state: %w", location, err)
|
||||
}
|
||||
switch {
|
||||
case stored.ID == uuid.Nil || stored.OrganizationID == uuid.Nil || stored.UserID == uuid.Nil:
|
||||
return Membership{}, fmt.Errorf("%s - identifiers must not be nil: %w", location, ErrInvalidMembership)
|
||||
case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt):
|
||||
return Membership{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidMembership)
|
||||
}
|
||||
return Membership{
|
||||
id: stored.ID,
|
||||
organizationID: stored.OrganizationID,
|
||||
userID: stored.UserID,
|
||||
role: role,
|
||||
state: state,
|
||||
createdAt: stored.CreatedAt,
|
||||
updatedAt: stored.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (membership Membership) ID() uuid.UUID { return membership.id }
|
||||
func (membership Membership) OrganizationID() uuid.UUID { return membership.organizationID }
|
||||
func (membership Membership) UserID() uuid.UUID { return membership.userID }
|
||||
func (membership Membership) Role() OrganizationRole { return membership.role }
|
||||
func (membership Membership) State() MembershipState { return membership.state }
|
||||
func (membership Membership) CreatedAt() time.Time { return membership.createdAt }
|
||||
func (membership Membership) UpdatedAt() time.Time { return membership.updatedAt }
|
||||
|
||||
// GrantsAccess reports whether the membership gives access to its
|
||||
// organization: it is active. It says nothing about what the role may do.
|
||||
func (membership Membership) GrantsAccess() bool { return membership.state.GrantsAccess() }
|
||||
|
||||
// CanManageOrganization reports whether the membership is active and its
|
||||
// role manages the organization.
|
||||
func (membership Membership) CanManageOrganization() bool {
|
||||
return membership.GrantsAccess() && membership.role.CanManageOrganization()
|
||||
}
|
||||
|
||||
// IsZero reports a Membership not built by NewMembership or
|
||||
// RestoreMembership.
|
||||
func (membership Membership) IsZero() bool { return membership.id == uuid.Nil }
|
||||
@@ -0,0 +1,116 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var membershipTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestParseOrganizationRoleAcceptsTheFourRolesOfTheContract(t *testing.T) {
|
||||
for _, value := range []string{"owner", "recruiter", "hiring_manager", "technical_expert"} {
|
||||
role, err := ParseOrganizationRole(value)
|
||||
if err != nil || string(role) != value {
|
||||
t.Fatalf("ParseOrganizationRole(%q) = %q, %v", value, role, err)
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"", "Owner", "admin", "manager", "tech_expert", "owner "} {
|
||||
if _, err := ParseOrganizationRole(value); !errors.Is(err, ErrInvalidMembership) {
|
||||
t.Fatalf("ParseOrganizationRole(%q) error = %v, want ErrInvalidMembership", value, err)
|
||||
}
|
||||
}
|
||||
if got := len(OrganizationRoles()); got != 4 {
|
||||
t.Fatalf("len(OrganizationRoles()) = %d, want 4", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyTheOwnerManagesTheOrganization(t *testing.T) {
|
||||
for _, role := range OrganizationRoles() {
|
||||
if got, want := role.CanManageOrganization(), role == OrganizationRoleOwner; got != want {
|
||||
t.Fatalf("%s.CanManageOrganization() = %v, want %v", role, got, want)
|
||||
}
|
||||
}
|
||||
if managers := ManagerRoles(); len(managers) != 1 || managers[0] != OrganizationRoleOwner {
|
||||
t.Fatalf("ManagerRoles() = %v, want only the owner", managers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAnActiveMembershipGrantsAccess(t *testing.T) {
|
||||
for _, value := range []string{"active", "suspended", "removed", "left"} {
|
||||
state, err := ParseMembershipState(value)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseMembershipState(%q) error = %v", value, err)
|
||||
}
|
||||
if state.GrantsAccess() != (value == "active") {
|
||||
t.Fatalf("%s.GrantsAccess() = %v, want true only for active", state, state.GrantsAccess())
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"", "invited", "Active", "revoked"} {
|
||||
if _, err := ParseMembershipState(value); !errors.Is(err, ErrInvalidMembership) {
|
||||
t.Fatalf("ParseMembershipState(%q) error = %v, want ErrInvalidMembership", value, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMembershipIsActiveAndNewOwnerMembershipIsTheOwner(t *testing.T) {
|
||||
organizationID, userID := uuid.New(), uuid.New()
|
||||
membership, err := NewMembership(MembershipInput{OrganizationID: organizationID, UserID: userID, Role: OrganizationRoleRecruiter, At: membershipTestTime})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
if membership.Role() != OrganizationRoleRecruiter || membership.State() != MembershipStateActive || !membership.GrantsAccess() ||
|
||||
membership.OrganizationID() != organizationID || membership.UserID() != userID || membership.ID().Version() != 7 ||
|
||||
membership.CanManageOrganization() {
|
||||
t.Fatalf("membership = %+v, want an active recruiter that cannot manage", membership)
|
||||
}
|
||||
owner, err := NewOwnerMembership(organizationID, userID, membershipTestTime)
|
||||
if err != nil || owner.Role() != OrganizationRoleOwner || !owner.CanManageOrganization() {
|
||||
t.Fatalf("NewOwnerMembership() = %+v, %v, want an active owner that manages", owner, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMembershipRejectsIncompleteInput(t *testing.T) {
|
||||
valid := MembershipInput{OrganizationID: uuid.New(), UserID: uuid.New(), Role: OrganizationRoleOwner, At: membershipTestTime}
|
||||
for name, change := range map[string]func(*MembershipInput){
|
||||
"nil organization": func(in *MembershipInput) { in.OrganizationID = uuid.Nil },
|
||||
"nil user": func(in *MembershipInput) { in.UserID = uuid.Nil },
|
||||
"unknown role": func(in *MembershipInput) { in.Role = "admin" },
|
||||
"empty role": func(in *MembershipInput) { in.Role = "" },
|
||||
"zero time": func(in *MembershipInput) { in.At = time.Time{} },
|
||||
} {
|
||||
input := valid
|
||||
change(&input)
|
||||
if _, err := NewMembership(input); !errors.Is(err, ErrInvalidMembership) {
|
||||
t.Fatalf("NewMembership(%s) error = %v, want ErrInvalidMembership", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreMembershipKeepsTheStoredStateAndRejectsInvalidRows(t *testing.T) {
|
||||
stored := StoredMembership{
|
||||
ID: uuid.New(), OrganizationID: uuid.New(), UserID: uuid.New(), Role: "owner", State: "removed",
|
||||
CreatedAt: membershipTestTime, UpdatedAt: membershipTestTime.Add(time.Hour),
|
||||
}
|
||||
membership, err := RestoreMembership(stored)
|
||||
if err != nil || membership.State() != MembershipStateRemoved || membership.GrantsAccess() || membership.CanManageOrganization() {
|
||||
t.Fatalf("RestoreMembership() = %+v, %v, want a removed owner without access", membership, err)
|
||||
}
|
||||
for name, change := range map[string]func(*StoredMembership){
|
||||
"unknown role": func(s *StoredMembership) { s.Role = "admin" },
|
||||
"unknown state": func(s *StoredMembership) { s.State = "invited" },
|
||||
"nil ID": func(s *StoredMembership) { s.ID = uuid.Nil },
|
||||
"nil organization": func(s *StoredMembership) { s.OrganizationID = uuid.Nil },
|
||||
"nil user": func(s *StoredMembership) { s.UserID = uuid.Nil },
|
||||
"update before create": func(s *StoredMembership) { s.UpdatedAt = membershipTestTime.Add(-time.Second) },
|
||||
"zero creation time": func(s *StoredMembership) { s.CreatedAt = time.Time{} },
|
||||
} {
|
||||
row := stored
|
||||
change(&row)
|
||||
if _, err := RestoreMembership(row); !errors.Is(err, ErrInvalidMembership) {
|
||||
t.Fatalf("RestoreMembership(%s) error = %v, want ErrInvalidMembership", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidOrganization reports an organization profile, verification, or
|
||||
// stored organization that breaks a rule.
|
||||
var ErrInvalidOrganization = errors.New("invalid organization")
|
||||
|
||||
// OrganizationFieldError reports the request field of an organization
|
||||
// profile that broke a rule. It matches ErrInvalidOrganization with
|
||||
// errors.Is, and an HTTP adapter reads Pointer with errors.As to answer 400
|
||||
// with the pointer of the field. Reason is fixed text; neither field quotes
|
||||
// the submitted value, which can be personal data.
|
||||
type OrganizationFieldError struct {
|
||||
// Pointer is the JSON Pointer of the field in the request body, such as
|
||||
// "/contacts/website" or "/representatives/2/name".
|
||||
Pointer string
|
||||
// Reason says which rule the field broke.
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (err *OrganizationFieldError) Error() string {
|
||||
return "organization field " + err.Pointer + " " + err.Reason
|
||||
}
|
||||
|
||||
func (err *OrganizationFieldError) Unwrap() error { return ErrInvalidOrganization }
|
||||
|
||||
func invalidOrganizationField(location, pointer, reason string) error {
|
||||
return fmt.Errorf("%s - %w", location, &OrganizationFieldError{Pointer: pointer, Reason: reason})
|
||||
}
|
||||
|
||||
const (
|
||||
// The bounds match the OrganizationDescription, OrganizationSphere,
|
||||
// OrganizationWebsite, and OrganizationRepresentative contract schemas
|
||||
// and the CHECK constraints of the organizations tables. The name bound,
|
||||
// maxOrganizationNameRunes, is shared with the consent snapshot of it.
|
||||
maxOrganizationDescriptionRunes = 2000
|
||||
maxOrganizationSphereRunes = 100
|
||||
maxOrganizationWebsiteRunes = 300
|
||||
maxOrganizationRepresentatives = 10
|
||||
maxRepresentativeNameRunes = 100
|
||||
maxRepresentativeJobTitleRunes = 100
|
||||
// maxHostnameBytes and maxHostnameLabelBytes follow RFC 1035.
|
||||
maxHostnameBytes = 253
|
||||
maxHostnameLabelBytes = 63
|
||||
httpsPrefix = "https://"
|
||||
)
|
||||
|
||||
var (
|
||||
// organizationPhonePattern is the E.164 format of ContactPhoneNumber.
|
||||
organizationPhonePattern = regexp.MustCompile(`^\+[1-9][0-9]{6,14}$`)
|
||||
// organizationTelegramPattern is the format of ContactTelegramUsername.
|
||||
organizationTelegramPattern = regexp.MustCompile(`^@[A-Za-z0-9_]{5,32}$`)
|
||||
)
|
||||
|
||||
// OrganizationVerificationLevel is the trust level of an organization (PRD
|
||||
// FR07). It starts at e0 and changes only through a verification process of
|
||||
// the server, never through a profile edit. Values match the
|
||||
// OrganizationVerificationLevel schema of the public contract.
|
||||
type OrganizationVerificationLevel string
|
||||
|
||||
const (
|
||||
// OrganizationVerificationE0 is the confirmed email of the creating
|
||||
// account; every organization starts here.
|
||||
OrganizationVerificationE0 OrganizationVerificationLevel = "e0"
|
||||
// OrganizationVerificationE1 is a corporate email, a verified domain, and
|
||||
// a link with the organization.
|
||||
OrganizationVerificationE1 OrganizationVerificationLevel = "e1"
|
||||
// OrganizationVerificationE2 is a check of the requisites and the
|
||||
// authority.
|
||||
OrganizationVerificationE2 OrganizationVerificationLevel = "e2"
|
||||
// OrganizationVerificationE3 is a manual check or a partner status.
|
||||
OrganizationVerificationE3 OrganizationVerificationLevel = "e3"
|
||||
)
|
||||
|
||||
// QuotaTier returns the quota tier of the level, and false for a level that
|
||||
// has no quota policy yet. The PRD gives E3 a separate policy, so it has no
|
||||
// tier.
|
||||
func (level OrganizationVerificationLevel) QuotaTier() (OrganizationTier, bool) {
|
||||
switch level {
|
||||
case OrganizationVerificationE0:
|
||||
return OrganizationTierE0, true
|
||||
case OrganizationVerificationE1:
|
||||
return OrganizationTierE1, true
|
||||
case OrganizationVerificationE2:
|
||||
return OrganizationTierE2, true
|
||||
case OrganizationVerificationE3:
|
||||
// The PRD gives E3 a separate policy, not a quota tier. A caller that
|
||||
// reads quotas (TASK-087) must fail closed on false: grant no quota
|
||||
// and refuse the action, never fall back to a lower or a default tier.
|
||||
return "", false
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// OrganizationVerificationBasis is the ground of a verification level. Each
|
||||
// level has its own bases. Values match the OrganizationVerificationBasis
|
||||
// schema of the public contract.
|
||||
type OrganizationVerificationBasis string
|
||||
|
||||
const (
|
||||
OrganizationBasisConfirmedEmail OrganizationVerificationBasis = "confirmed_email"
|
||||
OrganizationBasisCorporateDomain OrganizationVerificationBasis = "corporate_domain"
|
||||
OrganizationBasisRequisitesAndAuthority OrganizationVerificationBasis = "requisites_and_authority"
|
||||
OrganizationBasisManualReview OrganizationVerificationBasis = "manual_review"
|
||||
OrganizationBasisPartnerStatus OrganizationVerificationBasis = "partner_status"
|
||||
)
|
||||
|
||||
// OrganizationVerification is the verification level of an organization with
|
||||
// its ground and the time it was set. It has no setter and no constructor
|
||||
// but the initial one: a later verification process of the server will
|
||||
// construct the higher levels.
|
||||
type OrganizationVerification struct {
|
||||
level OrganizationVerificationLevel
|
||||
basis OrganizationVerificationBasis
|
||||
changedAt time.Time
|
||||
}
|
||||
|
||||
// InitialOrganizationVerification returns e0 on the ground of the confirmed
|
||||
// email, the level every new organization starts at.
|
||||
func InitialOrganizationVerification(at time.Time) (OrganizationVerification, error) {
|
||||
return RestoreOrganizationVerification(
|
||||
string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at)
|
||||
}
|
||||
|
||||
// RestoreOrganizationVerification validates a stored level, its basis, and
|
||||
// the time, and that the basis belongs to the level.
|
||||
func RestoreOrganizationVerification(level, basis string, changedAt time.Time) (OrganizationVerification, error) {
|
||||
const location = "domain.RestoreOrganizationVerification"
|
||||
var allowed []OrganizationVerificationBasis
|
||||
switch OrganizationVerificationLevel(level) {
|
||||
case OrganizationVerificationE0:
|
||||
allowed = []OrganizationVerificationBasis{OrganizationBasisConfirmedEmail}
|
||||
case OrganizationVerificationE1:
|
||||
allowed = []OrganizationVerificationBasis{OrganizationBasisCorporateDomain}
|
||||
case OrganizationVerificationE2:
|
||||
allowed = []OrganizationVerificationBasis{OrganizationBasisRequisitesAndAuthority}
|
||||
case OrganizationVerificationE3:
|
||||
allowed = []OrganizationVerificationBasis{OrganizationBasisManualReview, OrganizationBasisPartnerStatus}
|
||||
default:
|
||||
return OrganizationVerification{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
if !slices.Contains(allowed, OrganizationVerificationBasis(basis)) {
|
||||
return OrganizationVerification{}, fmt.Errorf("%s - the basis does not belong to the level: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
if changedAt.IsZero() {
|
||||
return OrganizationVerification{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
return OrganizationVerification{
|
||||
level: OrganizationVerificationLevel(level),
|
||||
basis: OrganizationVerificationBasis(basis),
|
||||
changedAt: changedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (verification OrganizationVerification) Level() OrganizationVerificationLevel {
|
||||
return verification.level
|
||||
}
|
||||
func (verification OrganizationVerification) Basis() OrganizationVerificationBasis {
|
||||
return verification.basis
|
||||
}
|
||||
func (verification OrganizationVerification) ChangedAt() time.Time { return verification.changedAt }
|
||||
|
||||
// OrganizationContactsInput holds the public contacts of an organization as
|
||||
// the request gave them; an empty string is a contact that is not set.
|
||||
type OrganizationContactsInput struct {
|
||||
Website string
|
||||
Email string
|
||||
Phone string
|
||||
Telegram string
|
||||
}
|
||||
|
||||
// OrganizationContacts are the public contacts of an organization: company
|
||||
// channels, never the personal contacts of an employee. The zero value has
|
||||
// no contact set.
|
||||
type OrganizationContacts struct {
|
||||
website string
|
||||
email string
|
||||
phone string
|
||||
telegram string
|
||||
}
|
||||
|
||||
// Website returns the https URL of the website, or "" when it is not set.
|
||||
func (contacts OrganizationContacts) Website() string { return contacts.website }
|
||||
|
||||
// Email returns the public mailbox, or "" when it is not set.
|
||||
func (contacts OrganizationContacts) Email() string { return contacts.email }
|
||||
|
||||
// Phone returns the E.164 phone number, or "" when it is not set.
|
||||
func (contacts OrganizationContacts) Phone() string { return contacts.phone }
|
||||
|
||||
// Telegram returns the Telegram username with the leading @, or "" when it
|
||||
// is not set.
|
||||
func (contacts OrganizationContacts) Telegram() string { return contacts.telegram }
|
||||
|
||||
// OrganizationRepresentativeInput is a representative as the request gave
|
||||
// it. The name is personal data of an employee: never log the value, and
|
||||
// never log a struct that holds it.
|
||||
type OrganizationRepresentativeInput struct {
|
||||
Name string
|
||||
JobTitle string
|
||||
}
|
||||
|
||||
// OrganizationRepresentative is a person that speaks for the organization to
|
||||
// candidates, as the owner presents them. It is presentation only: no
|
||||
// account link and no right. The name is personal data of an employee, so
|
||||
// String, GoString, Format, and LogValue redact the value; the fields sit
|
||||
// behind a pointer so that printing an enclosing struct shows only an
|
||||
// address.
|
||||
type OrganizationRepresentative struct {
|
||||
value *representativeValue
|
||||
}
|
||||
|
||||
type representativeValue struct {
|
||||
name string
|
||||
jobTitle string
|
||||
}
|
||||
|
||||
const redactedRepresentative = "[redacted representative]"
|
||||
|
||||
// Name returns the name as the card shows it.
|
||||
func (representative OrganizationRepresentative) Name() string {
|
||||
if representative.value == nil {
|
||||
return ""
|
||||
}
|
||||
return representative.value.name
|
||||
}
|
||||
|
||||
// JobTitle returns the position as the card shows it.
|
||||
func (representative OrganizationRepresentative) JobTitle() string {
|
||||
if representative.value == nil {
|
||||
return ""
|
||||
}
|
||||
return representative.value.jobTitle
|
||||
}
|
||||
|
||||
func (representative OrganizationRepresentative) String() string { return redactedRepresentative }
|
||||
|
||||
func (representative OrganizationRepresentative) GoString() string { return redactedRepresentative }
|
||||
|
||||
func (representative OrganizationRepresentative) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedRepresentative)
|
||||
}
|
||||
|
||||
func (representative OrganizationRepresentative) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedRepresentative)
|
||||
}
|
||||
|
||||
// OrganizationProfileInput is the editable profile of an organization as a
|
||||
// request gave it. An empty Description or Sphere is a field that is not
|
||||
// set. It holds the names of representatives, which are personal data of
|
||||
// employees: never log it.
|
||||
type OrganizationProfileInput struct {
|
||||
Name string
|
||||
Description string
|
||||
Sphere string
|
||||
Contacts OrganizationContactsInput
|
||||
Representatives []OrganizationRepresentativeInput
|
||||
}
|
||||
|
||||
// OrganizationProfile is the validated profile that the owner edits: the
|
||||
// name, the description, the field of business, the public contacts, and the
|
||||
// representatives. It holds no verification level, no role, and no member,
|
||||
// so changing it can neither raise a right nor raise the trust level.
|
||||
type OrganizationProfile struct {
|
||||
name string
|
||||
description string
|
||||
sphere string
|
||||
contacts OrganizationContacts
|
||||
representatives []OrganizationRepresentative
|
||||
}
|
||||
|
||||
// NewOrganizationProfile validates input and normalizes CRLF line breaks in
|
||||
// the description to LF. The first rule that fails returns an error
|
||||
// matching ErrInvalidOrganization with an *OrganizationFieldError that names
|
||||
// the field.
|
||||
func NewOrganizationProfile(input OrganizationProfileInput) (OrganizationProfile, error) {
|
||||
const location = "domain.NewOrganizationProfile"
|
||||
if reason := singleLineTextProblem(input.Name, maxOrganizationNameRunes); reason != "" {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, "/name", reason)
|
||||
}
|
||||
description := strings.ReplaceAll(input.Description, "\r\n", "\n")
|
||||
if description != "" {
|
||||
if reason := multiLineTextProblem(description, maxOrganizationDescriptionRunes); reason != "" {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, "/description", reason)
|
||||
}
|
||||
}
|
||||
if input.Sphere != "" {
|
||||
if reason := singleLineTextProblem(input.Sphere, maxOrganizationSphereRunes); reason != "" {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, "/sphere", reason)
|
||||
}
|
||||
}
|
||||
contacts, err := newOrganizationContacts(location, input.Contacts)
|
||||
if err != nil {
|
||||
return OrganizationProfile{}, err
|
||||
}
|
||||
if len(input.Representatives) > maxOrganizationRepresentatives {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, "/representatives",
|
||||
fmt.Sprintf("must have at most %d items", maxOrganizationRepresentatives))
|
||||
}
|
||||
representatives := make([]OrganizationRepresentative, 0, len(input.Representatives))
|
||||
for index, representative := range input.Representatives {
|
||||
pointer := fmt.Sprintf("/representatives/%d", index)
|
||||
if reason := singleLineTextProblem(representative.Name, maxRepresentativeNameRunes); reason != "" {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/name", reason)
|
||||
}
|
||||
if reason := singleLineTextProblem(representative.JobTitle, maxRepresentativeJobTitleRunes); reason != "" {
|
||||
return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/job_title", reason)
|
||||
}
|
||||
representatives = append(representatives, OrganizationRepresentative{
|
||||
value: &representativeValue{name: representative.Name, jobTitle: representative.JobTitle},
|
||||
})
|
||||
}
|
||||
return OrganizationProfile{
|
||||
name: input.Name,
|
||||
description: description,
|
||||
sphere: input.Sphere,
|
||||
contacts: contacts,
|
||||
representatives: representatives,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newOrganizationContacts(location string, input OrganizationContactsInput) (OrganizationContacts, error) {
|
||||
var contacts OrganizationContacts
|
||||
if input.Website != "" {
|
||||
if reason := websiteProblem(input.Website); reason != "" {
|
||||
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/website", reason)
|
||||
}
|
||||
contacts.website = input.Website
|
||||
}
|
||||
if input.Email != "" {
|
||||
email, err := NewEmailAddress(input.Email)
|
||||
if err != nil {
|
||||
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/email", "must be an email address")
|
||||
}
|
||||
contacts.email = email.Address()
|
||||
}
|
||||
if input.Phone != "" {
|
||||
if !organizationPhonePattern.MatchString(input.Phone) {
|
||||
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/phone", "must be an E.164 phone number")
|
||||
}
|
||||
contacts.phone = input.Phone
|
||||
}
|
||||
if input.Telegram != "" {
|
||||
if !organizationTelegramPattern.MatchString(input.Telegram) {
|
||||
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/telegram", "must be a Telegram username with the leading @")
|
||||
}
|
||||
contacts.telegram = input.Telegram
|
||||
}
|
||||
return contacts, nil
|
||||
}
|
||||
|
||||
func (profile OrganizationProfile) Name() string { return profile.name }
|
||||
|
||||
// Description returns the description, or "" when it is not set.
|
||||
func (profile OrganizationProfile) Description() string { return profile.description }
|
||||
|
||||
// Sphere returns the field of business, or "" when it is not set.
|
||||
func (profile OrganizationProfile) Sphere() string { return profile.sphere }
|
||||
|
||||
func (profile OrganizationProfile) Contacts() OrganizationContacts { return profile.contacts }
|
||||
|
||||
// Representatives returns a copy of the list in the order the owner gave it.
|
||||
func (profile OrganizationProfile) Representatives() []OrganizationRepresentative {
|
||||
return slices.Clone(profile.representatives)
|
||||
}
|
||||
|
||||
// Equal reports whether both profiles hold the same values, which tells a
|
||||
// change from a body that changes nothing.
|
||||
func (profile OrganizationProfile) Equal(other OrganizationProfile) bool {
|
||||
return profile.name == other.name &&
|
||||
profile.description == other.description &&
|
||||
profile.sphere == other.sphere &&
|
||||
profile.contacts == other.contacts &&
|
||||
slices.EqualFunc(profile.representatives, other.representatives, func(left, right OrganizationRepresentative) bool {
|
||||
return left.Name() == right.Name() && left.JobTitle() == right.JobTitle()
|
||||
})
|
||||
}
|
||||
|
||||
// singleLineTextProblem returns the rule that value breaks, or "" when it is
|
||||
// a valid single-line text: not empty, valid UTF-8, within maxRunes, without
|
||||
// surrounding whitespace, and without control characters.
|
||||
func singleLineTextProblem(value string, maxRunes int) string {
|
||||
switch {
|
||||
case value == "":
|
||||
return "must not be empty"
|
||||
case !utf8.ValidString(value):
|
||||
return "must be valid UTF-8"
|
||||
case utf8.RuneCountInString(value) > maxRunes:
|
||||
return fmt.Sprintf("must have at most %d characters", maxRunes)
|
||||
case strings.TrimSpace(value) != value:
|
||||
return "must not have leading or trailing whitespace"
|
||||
case strings.ContainsFunc(value, isForbiddenTextRune):
|
||||
return "must not contain control characters"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// multiLineTextProblem is singleLineTextProblem for a text that may contain
|
||||
// LF line breaks.
|
||||
func multiLineTextProblem(value string, maxRunes int) string {
|
||||
switch {
|
||||
case !utf8.ValidString(value):
|
||||
return "must be valid UTF-8"
|
||||
case utf8.RuneCountInString(value) > maxRunes:
|
||||
return fmt.Sprintf("must have at most %d characters", maxRunes)
|
||||
case strings.TrimSpace(value) != value:
|
||||
return "must not have leading or trailing whitespace"
|
||||
case strings.ContainsFunc(value, func(character rune) bool { return character != '\n' && isForbiddenTextRune(character) }):
|
||||
return "must not contain control characters"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// isForbiddenTextRune reports a control character or a Unicode line or
|
||||
// paragraph separator, which break one-line text and which the database
|
||||
// refuses in its control character class.
|
||||
func isForbiddenTextRune(character rune) bool {
|
||||
return unicode.IsControl(character) || character == '\u2028' || character == '\u2029'
|
||||
}
|
||||
|
||||
// websiteProblem returns the rule that value breaks, or "" when it is an
|
||||
// https URL of a host name: no credentials, no port, no IP address, and a
|
||||
// host with at least two labels whose last one starts with a letter. The
|
||||
// server never fetches the address; a later feature that does must resolve
|
||||
// it and refuse private ranges on its own.
|
||||
func websiteProblem(value string) string {
|
||||
switch {
|
||||
case utf8.RuneCountInString(value) > maxOrganizationWebsiteRunes:
|
||||
return fmt.Sprintf("must have at most %d characters", maxOrganizationWebsiteRunes)
|
||||
case !strings.HasPrefix(value, httpsPrefix):
|
||||
return "must be an https URL"
|
||||
case strings.ContainsFunc(value, func(character rune) bool { return unicode.IsSpace(character) || isForbiddenTextRune(character) }):
|
||||
return "must not contain whitespace or control characters"
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
switch {
|
||||
case err != nil || parsed.Opaque != "":
|
||||
return "must be an https URL"
|
||||
case parsed.User != nil:
|
||||
return "must not contain credentials"
|
||||
case parsed.Port() != "":
|
||||
return "must not contain a port"
|
||||
}
|
||||
return hostnameProblem(parsed.Hostname())
|
||||
}
|
||||
|
||||
func hostnameProblem(host string) string {
|
||||
const notHostName = "must have a host name"
|
||||
if host == "" || len(host) > maxHostnameBytes || net.ParseIP(host) != nil {
|
||||
return notHostName
|
||||
}
|
||||
labels := strings.Split(host, ".")
|
||||
if len(labels) < 2 {
|
||||
return notHostName
|
||||
}
|
||||
for _, label := range labels {
|
||||
if label == "" || len(label) > maxHostnameLabelBytes ||
|
||||
strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
|
||||
return notHostName
|
||||
}
|
||||
for _, character := range label {
|
||||
if character != '-' && !unicode.IsLetter(character) && !unicode.IsDigit(character) {
|
||||
return notHostName
|
||||
}
|
||||
}
|
||||
}
|
||||
// A top-level domain starts with a letter, which also refuses numeric
|
||||
// spellings of an IP address such as 127.1 or 0x7f.1.
|
||||
if first, _ := utf8.DecodeRuneInString(labels[len(labels)-1]); !unicode.IsLetter(first) {
|
||||
return notHostName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// OrganizationCandidateCard is the card of an organization as a candidate sees
|
||||
// it. It carries the profile and the verification level only: no version, no
|
||||
// time, no ground of the verification, no member, no role, and no account.
|
||||
type OrganizationCandidateCard struct {
|
||||
id uuid.UUID
|
||||
profile OrganizationProfile
|
||||
level OrganizationVerificationLevel
|
||||
}
|
||||
|
||||
func (card OrganizationCandidateCard) ID() uuid.UUID { return card.id }
|
||||
func (card OrganizationCandidateCard) Profile() OrganizationProfile { return card.profile }
|
||||
func (card OrganizationCandidateCard) VerificationLevel() OrganizationVerificationLevel {
|
||||
return card.level
|
||||
}
|
||||
|
||||
// Organization is a company that employer accounts work in: the profile its
|
||||
// owner edits and the verification level that only the server sets. It holds
|
||||
// no membership and no role; those belong to Membership. Storage
|
||||
// reconstructs it from trusted rows with RestoreOrganization; new ones come
|
||||
// from NewOrganization.
|
||||
type Organization struct {
|
||||
id uuid.UUID
|
||||
profile OrganizationProfile
|
||||
verification OrganizationVerification
|
||||
// version is the optimistic concurrency version of the profile. Storage
|
||||
// checks it as the expected version and advances it in the same
|
||||
// statement, so a domain method never changes it.
|
||||
version int64
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
// NewOrganization creates an organization at version 1 with a time-ordered
|
||||
// UUIDv7 identifier and the initial verification level e0. No input chooses
|
||||
// the level: a company that looks verified still starts at e0.
|
||||
func NewOrganization(profile OrganizationProfile, createdAt time.Time) (Organization, error) {
|
||||
const location = "domain.NewOrganization"
|
||||
if profile.name == "" {
|
||||
return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
verification, err := InitialOrganizationVerification(createdAt)
|
||||
if err != nil {
|
||||
return Organization{}, fmt.Errorf("%s - set the initial verification: %w", location, err)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Organization{}, fmt.Errorf("%s - generate organization ID: %w", location, err)
|
||||
}
|
||||
return Organization{
|
||||
id: id,
|
||||
profile: profile,
|
||||
verification: verification,
|
||||
version: 1,
|
||||
createdAt: createdAt,
|
||||
updatedAt: createdAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StoredRepresentative carries the columns of a stored representative. The
|
||||
// name is personal data of an employee: never log the value, and never log a
|
||||
// struct that holds it.
|
||||
type StoredRepresentative struct {
|
||||
Name string
|
||||
JobTitle string
|
||||
}
|
||||
|
||||
// StoredOrganization carries the columns of a stored organization with its
|
||||
// representatives in list order. An empty Description, Sphere, or contact is
|
||||
// a column that is NULL.
|
||||
type StoredOrganization struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Description string
|
||||
Sphere string
|
||||
Website string
|
||||
Email string
|
||||
Phone string
|
||||
Telegram string
|
||||
Representatives []StoredRepresentative
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt time.Time
|
||||
Version int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// RestoreOrganization validates a stored organization with the rules of
|
||||
// NewOrganizationProfile and the verification rules, so a row changed
|
||||
// outside the application fails with ErrInvalidOrganization.
|
||||
func RestoreOrganization(stored StoredOrganization) (Organization, error) {
|
||||
const location = "domain.RestoreOrganization"
|
||||
representatives := make([]OrganizationRepresentativeInput, 0, len(stored.Representatives))
|
||||
for _, representative := range stored.Representatives {
|
||||
representatives = append(representatives, OrganizationRepresentativeInput(representative))
|
||||
}
|
||||
profile, err := NewOrganizationProfile(OrganizationProfileInput{
|
||||
Name: stored.Name,
|
||||
Description: stored.Description,
|
||||
Sphere: stored.Sphere,
|
||||
Contacts: OrganizationContactsInput{
|
||||
Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram,
|
||||
},
|
||||
Representatives: representatives,
|
||||
})
|
||||
if err != nil {
|
||||
return Organization{}, fmt.Errorf("%s - validate profile: %w", location, err)
|
||||
}
|
||||
verification, err := RestoreOrganizationVerification(stored.VerificationLevel, stored.VerificationBasis, stored.VerificationChangedAt)
|
||||
if err != nil {
|
||||
return Organization{}, fmt.Errorf("%s - validate verification: %w", location, err)
|
||||
}
|
||||
switch {
|
||||
case stored.ID == uuid.Nil:
|
||||
return Organization{}, fmt.Errorf("%s - ID must not be nil: %w", location, ErrInvalidOrganization)
|
||||
case stored.Version < 1:
|
||||
return Organization{}, fmt.Errorf("%s - version must be positive: %w", location, ErrInvalidOrganization)
|
||||
case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt):
|
||||
return Organization{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
return Organization{
|
||||
id: stored.ID,
|
||||
profile: profile,
|
||||
verification: verification,
|
||||
version: stored.Version,
|
||||
createdAt: stored.CreatedAt,
|
||||
updatedAt: stored.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (organization Organization) ID() uuid.UUID { return organization.id }
|
||||
func (organization Organization) Profile() OrganizationProfile { return organization.profile }
|
||||
func (organization Organization) Verification() OrganizationVerification {
|
||||
return organization.verification
|
||||
}
|
||||
func (organization Organization) Version() int64 { return organization.version }
|
||||
func (organization Organization) CreatedAt() time.Time { return organization.createdAt }
|
||||
func (organization Organization) UpdatedAt() time.Time { return organization.updatedAt }
|
||||
|
||||
// ApplyProfile returns the organization with profile as its profile. The
|
||||
// identifier, the version, and the verification stay as they are: storage
|
||||
// checks Version as the expected version and advances it, and only a
|
||||
// verification process changes the level. A time before the last update,
|
||||
// from clock skew between instances, is stored as the last update.
|
||||
func (organization Organization) ApplyProfile(profile OrganizationProfile, at time.Time) (Organization, error) {
|
||||
const location = "Organization.ApplyProfile"
|
||||
switch {
|
||||
case organization.id == uuid.Nil:
|
||||
return Organization{}, fmt.Errorf("%s - organization must be built by NewOrganization: %w", location, ErrInvalidOrganization)
|
||||
case profile.name == "":
|
||||
return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization)
|
||||
case at.IsZero():
|
||||
return Organization{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
updated := organization
|
||||
updated.profile = profile
|
||||
updated.updatedAt = at
|
||||
if at.Before(organization.updatedAt) {
|
||||
updated.updatedAt = organization.updatedAt
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// CandidateCard returns the card of the organization as a candidate sees it.
|
||||
func (organization Organization) CandidateCard() OrganizationCandidateCard {
|
||||
return OrganizationCandidateCard{id: organization.id, profile: organization.profile, level: organization.verification.level}
|
||||
}
|
||||
|
||||
// IsZero reports an Organization not built by NewOrganization or
|
||||
// RestoreOrganization.
|
||||
func (organization Organization) IsZero() bool { return organization.id == uuid.Nil }
|
||||
|
||||
// LogValue logs the identifier, the version, and the level only: the
|
||||
// profile holds representatives' names, which are personal data.
|
||||
func (organization Organization) LogValue() slog.Value {
|
||||
return slog.GroupValue(
|
||||
slog.String("id", organization.id.String()),
|
||||
slog.Int64("version", organization.version),
|
||||
slog.String("verification_level", string(organization.verification.level)),
|
||||
)
|
||||
}
|
||||
|
||||
// OrganizationSummary is an organization as the list of an account's
|
||||
// organizations names it.
|
||||
type OrganizationSummary struct {
|
||||
id uuid.UUID
|
||||
name string
|
||||
level OrganizationVerificationLevel
|
||||
}
|
||||
|
||||
// RestoreOrganizationSummary validates a stored name and level.
|
||||
func RestoreOrganizationSummary(id uuid.UUID, name, level string) (OrganizationSummary, error) {
|
||||
const location = "domain.RestoreOrganizationSummary"
|
||||
if singleLineTextProblem(name, maxOrganizationNameRunes) != "" || id == uuid.Nil {
|
||||
return OrganizationSummary{}, fmt.Errorf("%s - ID and name must be valid: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
switch OrganizationVerificationLevel(level) {
|
||||
case OrganizationVerificationE0, OrganizationVerificationE1, OrganizationVerificationE2, OrganizationVerificationE3:
|
||||
return OrganizationSummary{id: id, name: name, level: OrganizationVerificationLevel(level)}, nil
|
||||
default:
|
||||
return OrganizationSummary{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
}
|
||||
|
||||
func (summary OrganizationSummary) ID() uuid.UUID { return summary.id }
|
||||
func (summary OrganizationSummary) Name() string { return summary.name }
|
||||
func (summary OrganizationSummary) VerificationLevel() OrganizationVerificationLevel {
|
||||
return summary.level
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var organizationTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
func completeOrganizationProfileInput() OrganizationProfileInput {
|
||||
return OrganizationProfileInput{
|
||||
Name: "ООО Пример Платежи",
|
||||
Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.",
|
||||
Sphere: "Платежи и финансовые сервисы",
|
||||
Contacts: OrganizationContactsInput{
|
||||
Website: "https://payments.example.com/careers?team=core",
|
||||
Email: "careers@payments.example.com",
|
||||
Phone: "+74950000000",
|
||||
Telegram: "@payments_careers",
|
||||
},
|
||||
Representatives: []OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Руководитель по подбору"}},
|
||||
}
|
||||
}
|
||||
|
||||
func mustOrganizationProfile(t *testing.T, input OrganizationProfileInput) OrganizationProfile {
|
||||
t.Helper()
|
||||
profile, err := NewOrganizationProfile(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v", err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func TestNewOrganizationProfileAcceptsACompleteAndAMinimalProfile(t *testing.T) {
|
||||
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
|
||||
if profile.Name() != "ООО Пример Платежи" || profile.Sphere() != "Платежи и финансовые сервисы" ||
|
||||
profile.Contacts().Website() != "https://payments.example.com/careers?team=core" ||
|
||||
profile.Contacts().Phone() != "+74950000000" || profile.Contacts().Telegram() != "@payments_careers" ||
|
||||
profile.Contacts().Email() != "careers@payments.example.com" {
|
||||
t.Fatalf("profile = %+v, want the given values", profile)
|
||||
}
|
||||
if representatives := profile.Representatives(); len(representatives) != 1 || representatives[0].Name() != "Анна Тестова" ||
|
||||
representatives[0].JobTitle() != "Руководитель по подбору" {
|
||||
t.Fatalf("representatives = %v, want the given one", representatives)
|
||||
}
|
||||
|
||||
minimal := mustOrganizationProfile(t, OrganizationProfileInput{Name: "A"})
|
||||
if minimal.Description() != "" || minimal.Sphere() != "" || minimal.Contacts() != (OrganizationContacts{}) || len(minimal.Representatives()) != 0 {
|
||||
t.Fatalf("minimal profile = %+v, want every optional field unset", minimal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewOrganizationProfileNormalizesDescriptionLineBreaks(t *testing.T) {
|
||||
input := completeOrganizationProfileInput()
|
||||
input.Description = "first\r\nsecond"
|
||||
if got := mustOrganizationProfile(t, input).Description(); got != "first\nsecond" {
|
||||
t.Fatalf("Description() = %q, want CRLF stored as LF", got)
|
||||
}
|
||||
input.Description = "first\rsecond"
|
||||
if _, err := NewOrganizationProfile(input); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("NewOrganizationProfile(lone CR) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewOrganizationProfileNamesTheFieldThatBreaksARule(t *testing.T) {
|
||||
longName := strings.Repeat("я", maxOrganizationNameRunes+1)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change func(*OrganizationProfileInput)
|
||||
pointer string
|
||||
}{
|
||||
{"empty name", func(in *OrganizationProfileInput) { in.Name = "" }, "/name"},
|
||||
{"name with a leading space", func(in *OrganizationProfileInput) { in.Name = " ООО" }, "/name"},
|
||||
{"name with a trailing tab", func(in *OrganizationProfileInput) { in.Name = "ООО\t" }, "/name"},
|
||||
{"name with a line break", func(in *OrganizationProfileInput) { in.Name = "ООО\nПример" }, "/name"},
|
||||
{"name with a line separator", func(in *OrganizationProfileInput) { in.Name = "ООО\u2028Пример" }, "/name"},
|
||||
{"name over 200 characters", func(in *OrganizationProfileInput) { in.Name = longName }, "/name"},
|
||||
{"name that is not UTF-8", func(in *OrganizationProfileInput) { in.Name = "ООО\xff" }, "/name"},
|
||||
{"description with a leading line break", func(in *OrganizationProfileInput) { in.Description = "\nтекст" }, "/description"},
|
||||
{"description with a control character", func(in *OrganizationProfileInput) { in.Description = "текст\x07" }, "/description"},
|
||||
{"description over 2000 characters", func(in *OrganizationProfileInput) {
|
||||
in.Description = strings.Repeat("я", maxOrganizationDescriptionRunes+1)
|
||||
}, "/description"},
|
||||
{"sphere with a line break", func(in *OrganizationProfileInput) { in.Sphere = "Платежи\nи сервисы" }, "/sphere"},
|
||||
{"website over http", func(in *OrganizationProfileInput) { in.Contacts.Website = "http://payments.example.com" }, "/contacts/website"},
|
||||
{"website in capitals scheme", func(in *OrganizationProfileInput) { in.Contacts.Website = "HTTPS://payments.example.com" }, "/contacts/website"},
|
||||
{"website with credentials", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://user:secret@payments.example.com" }, "/contacts/website"},
|
||||
{"website with a port", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com:8443" }, "/contacts/website"},
|
||||
{"website with an IPv4 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://10.0.0.5/admin" }, "/contacts/website"},
|
||||
{"website with an IPv6 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://[::1]/" }, "/contacts/website"},
|
||||
{"website with a short numeric host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://127.1" }, "/contacts/website"},
|
||||
{"website with a hexadecimal host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://0x7f.0x1" }, "/contacts/website"},
|
||||
{"website without a dot", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://localhost/" }, "/contacts/website"},
|
||||
{"website with a space", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com/a b" }, "/contacts/website"},
|
||||
{"website with an empty label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments..example.com" }, "/contacts/website"},
|
||||
{"website with a hyphen-led label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://-payments.example.com" }, "/contacts/website"},
|
||||
{"website with an underscore", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://pay_ments.example.com" }, "/contacts/website"},
|
||||
{"website over 300 characters", func(in *OrganizationProfileInput) {
|
||||
in.Contacts.Website = "https://payments.example.com/" + strings.Repeat("a", 300)
|
||||
}, "/contacts/website"},
|
||||
{"email without a domain dot", func(in *OrganizationProfileInput) { in.Contacts.Email = "careers@payments" }, "/contacts/email"},
|
||||
{"email with a display name", func(in *OrganizationProfileInput) { in.Contacts.Email = "HR <careers@payments.example.com>" }, "/contacts/email"},
|
||||
{"phone without a plus", func(in *OrganizationProfileInput) { in.Contacts.Phone = "74950000000" }, "/contacts/phone"},
|
||||
{"phone with spaces", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+7 495 000 00 00" }, "/contacts/phone"},
|
||||
{"phone with a leading zero country code", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+04950000000" }, "/contacts/phone"},
|
||||
{"telegram without an at sign", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "payments_careers" }, "/contacts/telegram"},
|
||||
{"telegram that is too short", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "@abc" }, "/contacts/telegram"},
|
||||
{"eleven representatives", func(in *OrganizationProfileInput) {
|
||||
in.Representatives = make([]OrganizationRepresentativeInput, maxOrganizationRepresentatives+1)
|
||||
for index := range in.Representatives {
|
||||
in.Representatives[index] = OrganizationRepresentativeInput{Name: "Имя", JobTitle: "Должность"}
|
||||
}
|
||||
}, "/representatives"},
|
||||
{"representative with an empty name", func(in *OrganizationProfileInput) {
|
||||
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: "HR"}, {Name: "", JobTitle: "HR"}}
|
||||
}, "/representatives/1/name"},
|
||||
{"representative with a padded job title", func(in *OrganizationProfileInput) {
|
||||
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: " HR"}}
|
||||
}, "/representatives/0/job_title"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := completeOrganizationProfileInput()
|
||||
test.change(&input)
|
||||
|
||||
_, err := NewOrganizationProfile(input)
|
||||
if !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
var fieldError *OrganizationFieldError
|
||||
if !errors.As(err, &fieldError) || fieldError.Pointer != test.pointer {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v, want the pointer %s", err, test.pointer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationFieldErrorDoesNotQuoteTheSubmittedValue(t *testing.T) {
|
||||
const secret = "Конфиденциальная Фамилия"
|
||||
input := completeOrganizationProfileInput()
|
||||
input.Representatives = []OrganizationRepresentativeInput{{Name: secret, JobTitle: " " + secret}}
|
||||
|
||||
_, err := NewOrganizationProfile(input)
|
||||
if err == nil || strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v, want an error without the submitted value", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewOrganizationProfileAcceptsInternationalizedAndPathWebsites(t *testing.T) {
|
||||
for _, website := range []string{
|
||||
"https://example.com",
|
||||
"https://пример.рф/vacancies",
|
||||
"https://xn--e1afmkfd.xn--p1ai",
|
||||
"https://careers.example.co.uk/a/b?c=d#e",
|
||||
} {
|
||||
input := OrganizationProfileInput{Name: "A", Contacts: OrganizationContactsInput{Website: website}}
|
||||
if _, err := NewOrganizationProfile(input); err != nil {
|
||||
t.Fatalf("NewOrganizationProfile(%q) error = %v, want it accepted", website, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationProfileCopiesItsRepresentatives(t *testing.T) {
|
||||
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
|
||||
representatives := profile.Representatives()
|
||||
representatives[0] = OrganizationRepresentative{}
|
||||
if profile.Representatives()[0].Name() != "Анна Тестова" {
|
||||
t.Fatal("changing the returned slice changed the profile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationProfileEqualTellsAChangeFromNoChange(t *testing.T) {
|
||||
base := completeOrganizationProfileInput()
|
||||
profile := mustOrganizationProfile(t, base)
|
||||
if !profile.Equal(mustOrganizationProfile(t, base)) {
|
||||
t.Fatal("equal inputs give unequal profiles")
|
||||
}
|
||||
for name, change := range map[string]func(*OrganizationProfileInput){
|
||||
"name": func(in *OrganizationProfileInput) { in.Name = "Другое имя" },
|
||||
"description": func(in *OrganizationProfileInput) { in.Description = "" },
|
||||
"contact": func(in *OrganizationProfileInput) { in.Contacts.Phone = "" },
|
||||
"representative": func(in *OrganizationProfileInput) { in.Representatives[0].JobTitle = "Директор" },
|
||||
"list length": func(in *OrganizationProfileInput) { in.Representatives = nil },
|
||||
} {
|
||||
input := base
|
||||
input.Representatives = append([]OrganizationRepresentativeInput(nil), base.Representatives...)
|
||||
change(&input)
|
||||
if profile.Equal(mustOrganizationProfile(t, input)) {
|
||||
t.Fatalf("a changed %s still compares equal", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewOrganizationStartsAtE0WhateverTheProfileLooksLike(t *testing.T) {
|
||||
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
|
||||
|
||||
organization, err := NewOrganization(profile, organizationTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
verification := organization.Verification()
|
||||
if verification.Level() != OrganizationVerificationE0 || verification.Basis() != OrganizationBasisConfirmedEmail ||
|
||||
!verification.ChangedAt().Equal(organizationTestTime) {
|
||||
t.Fatalf("verification = %s %s %s, want e0 on the confirmed email at the creation time",
|
||||
verification.Level(), verification.Basis(), verification.ChangedAt())
|
||||
}
|
||||
if organization.Version() != 1 || organization.ID().Version() != 7 || !organization.CreatedAt().Equal(organizationTestTime) ||
|
||||
!organization.UpdatedAt().Equal(organizationTestTime) {
|
||||
t.Fatalf("organization = %v, want version 1, a UUIDv7, and the creation time", organization)
|
||||
}
|
||||
if _, err := NewOrganization(OrganizationProfile{}, organizationTestTime); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("NewOrganization(zero profile) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
if _, err := NewOrganization(profile, time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("NewOrganization(zero time) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyProfileKeepsTheVerificationVersionAndIdentity(t *testing.T) {
|
||||
organization, err := NewOrganization(mustOrganizationProfile(t, OrganizationProfileInput{Name: "Старое имя"}), organizationTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
later := organizationTestTime.Add(time.Hour)
|
||||
|
||||
updated, err := organization.ApplyProfile(mustOrganizationProfile(t, completeOrganizationProfileInput()), later)
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyProfile() error = %v", err)
|
||||
}
|
||||
if updated.ID() != organization.ID() || updated.Version() != organization.Version() || updated.Verification() != organization.Verification() ||
|
||||
!updated.CreatedAt().Equal(organizationTestTime) || !updated.UpdatedAt().Equal(later) {
|
||||
t.Fatalf("updated = %v, want the same identity, version, and verification and the new update time", updated)
|
||||
}
|
||||
if updated.Profile().Name() != "ООО Пример Платежи" || organization.Profile().Name() != "Старое имя" {
|
||||
t.Fatal("ApplyProfile changed the receiver or did not apply the profile")
|
||||
}
|
||||
|
||||
// Clock skew between instances never moves the update time backwards.
|
||||
skewed, err := updated.ApplyProfile(updated.Profile(), organizationTestTime)
|
||||
if err != nil || !skewed.UpdatedAt().Equal(later) {
|
||||
t.Fatalf("ApplyProfile(earlier time) = %v, %v, want the last update time kept", skewed.UpdatedAt(), err)
|
||||
}
|
||||
if _, err := organization.ApplyProfile(OrganizationProfile{}, later); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("ApplyProfile(zero profile) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
if _, err := (Organization{}).ApplyProfile(updated.Profile(), later); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("ApplyProfile on a zero organization error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreOrganizationVerificationAllowsOnlyTheBasesOfALevel(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
level, basis string
|
||||
ok bool
|
||||
}{
|
||||
{"e0", "confirmed_email", true},
|
||||
{"e1", "corporate_domain", true},
|
||||
{"e2", "requisites_and_authority", true},
|
||||
{"e3", "manual_review", true},
|
||||
{"e3", "partner_status", true},
|
||||
{"e0", "corporate_domain", false},
|
||||
{"e1", "confirmed_email", false},
|
||||
{"e2", "manual_review", false},
|
||||
{"e4", "manual_review", false},
|
||||
{"", "", false},
|
||||
} {
|
||||
_, err := RestoreOrganizationVerification(test.level, test.basis, organizationTestTime)
|
||||
if (err == nil) != test.ok || (err != nil && !errors.Is(err, ErrInvalidOrganization)) {
|
||||
t.Fatalf("RestoreOrganizationVerification(%q, %q) error = %v, want ok = %v", test.level, test.basis, err, test.ok)
|
||||
}
|
||||
}
|
||||
if _, err := RestoreOrganizationVerification("e0", "confirmed_email", time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("RestoreOrganizationVerification(zero time) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationLevelMapsToTheQuotaTiersOfThePolicy(t *testing.T) {
|
||||
for level, want := range map[OrganizationVerificationLevel]OrganizationTier{
|
||||
OrganizationVerificationE0: OrganizationTierE0,
|
||||
OrganizationVerificationE1: OrganizationTierE1,
|
||||
OrganizationVerificationE2: OrganizationTierE2,
|
||||
} {
|
||||
if tier, ok := level.QuotaTier(); !ok || tier != want {
|
||||
t.Fatalf("%s.QuotaTier() = %q, %v, want %q", level, tier, ok, want)
|
||||
}
|
||||
}
|
||||
if _, ok := OrganizationVerificationE3.QuotaTier(); ok {
|
||||
t.Fatal("e3 has a quota tier, but the PRD gives it a separate policy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreOrganizationRejectsARowChangedOutsideTheApplication(t *testing.T) {
|
||||
valid := func() StoredOrganization {
|
||||
return StoredOrganization{
|
||||
ID: uuid.New(), Name: "ООО Пример", Version: 1,
|
||||
VerificationLevel: "e0", VerificationBasis: "confirmed_email", VerificationChangedAt: organizationTestTime,
|
||||
CreatedAt: organizationTestTime, UpdatedAt: organizationTestTime,
|
||||
}
|
||||
}
|
||||
if _, err := RestoreOrganization(valid()); err != nil {
|
||||
t.Fatalf("RestoreOrganization(valid) error = %v", err)
|
||||
}
|
||||
for name, change := range map[string]func(*StoredOrganization){
|
||||
"nil ID": func(s *StoredOrganization) { s.ID = uuid.Nil },
|
||||
"empty name": func(s *StoredOrganization) { s.Name = "" },
|
||||
"version zero": func(s *StoredOrganization) { s.Version = 0 },
|
||||
"unknown level": func(s *StoredOrganization) { s.VerificationLevel = "e9" },
|
||||
"basis of another level": func(s *StoredOrganization) { s.VerificationBasis = "manual_review" },
|
||||
"update before creation": func(s *StoredOrganization) { s.UpdatedAt = organizationTestTime.Add(-time.Second) },
|
||||
"invalid website": func(s *StoredOrganization) { s.Website = "http://example.com" },
|
||||
"too many representative": func(s *StoredOrganization) { s.Representatives = make([]StoredRepresentative, 11) },
|
||||
} {
|
||||
stored := valid()
|
||||
change(&stored)
|
||||
if _, err := RestoreOrganization(stored); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("RestoreOrganization(%s) error = %v, want ErrInvalidOrganization", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateCardHoldsTheProfileAndTheLevelOnly(t *testing.T) {
|
||||
organization, err := NewOrganization(mustOrganizationProfile(t, completeOrganizationProfileInput()), organizationTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
card := organization.CandidateCard()
|
||||
if card.ID() != organization.ID() || !card.Profile().Equal(organization.Profile()) || card.VerificationLevel() != OrganizationVerificationE0 {
|
||||
t.Fatalf("card = %+v, want the id, the profile, and the level of the organization", card)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepresentativesAndOrganizationsAreRedactedInLogsAndFormatting(t *testing.T) {
|
||||
const name = "Конфиденциальная Фамилия"
|
||||
profile := mustOrganizationProfile(t, OrganizationProfileInput{
|
||||
Name: "ООО Пример",
|
||||
Representatives: []OrganizationRepresentativeInput{{Name: name, JobTitle: "Руководитель"}},
|
||||
})
|
||||
organization, err := NewOrganization(profile, organizationTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
representative := profile.Representatives()[0]
|
||||
type enclosing struct {
|
||||
Representative OrganizationRepresentative
|
||||
Hidden []OrganizationRepresentative
|
||||
}
|
||||
wrapped := enclosing{Representative: representative, Hidden: profile.Representatives()}
|
||||
|
||||
var logs bytes.Buffer
|
||||
for _, logger := range []*slog.Logger{slog.New(slog.NewTextHandler(&logs, nil)), slog.New(slog.NewJSONHandler(&logs, nil))} {
|
||||
logger.Info("organization", "representative", representative, "organization", organization)
|
||||
}
|
||||
output := fmt.Sprintf("%v %+v %#v %s %v %+v", representative, representative, representative, representative, wrapped, wrapped) + logs.String()
|
||||
for _, secret := range []string{name, "Руководитель"} {
|
||||
if strings.Contains(output, secret) {
|
||||
t.Fatalf("printing a representative exposes %q: %s", secret, output)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(logs.String(), `"verification_level":"e0"`) {
|
||||
t.Fatalf("logs = %s, want the organization logged by id, version, and level", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreOrganizationSummaryValidatesTheNameAndTheLevel(t *testing.T) {
|
||||
id := uuid.New()
|
||||
if summary, err := RestoreOrganizationSummary(id, "ООО Пример", "e1"); err != nil || summary.ID() != id ||
|
||||
summary.Name() != "ООО Пример" || summary.VerificationLevel() != OrganizationVerificationE1 {
|
||||
t.Fatalf("RestoreOrganizationSummary() = %+v, %v, want the stored values", summary, err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
id uuid.UUID
|
||||
name, level string
|
||||
}{
|
||||
{uuid.Nil, "ООО", "e0"},
|
||||
{id, "", "e0"},
|
||||
{id, " ООО", "e0"},
|
||||
{id, "ООО", "e5"},
|
||||
} {
|
||||
if _, err := RestoreOrganizationSummary(test.id, test.name, test.level); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("RestoreOrganizationSummary(%v, %q, %q) error = %v, want ErrInvalidOrganization", test.id, test.name, test.level, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrOrganizationNotFound reports that the organization does not exist or
|
||||
// that the account has no active membership in it. The two cases are the
|
||||
// same on purpose, so a caller cannot tell an organization that exists
|
||||
// from one that it may not enter.
|
||||
ErrOrganizationNotFound = errors.New("organization not found")
|
||||
|
||||
// ErrOrganizationManagerRequired reports an account whose active
|
||||
// membership does not have a role that manages the organization.
|
||||
ErrOrganizationManagerRequired = errors.New("membership role cannot manage the organization")
|
||||
|
||||
// ErrOrganizationVersionConflict reports that the expected version of an
|
||||
// organization is stale: another change advanced it. Nothing was changed;
|
||||
// read the organization again.
|
||||
ErrOrganizationVersionConflict = errors.New("organization changed concurrently")
|
||||
|
||||
// ErrMembershipExists reports a second membership for an account and
|
||||
// organization that already have one, in any state.
|
||||
ErrMembershipExists = errors.New("membership already exists")
|
||||
|
||||
// ErrMembershipNotFound reports that the account has no membership in the
|
||||
// organization, in any state.
|
||||
ErrMembershipNotFound = errors.New("membership not found")
|
||||
)
|
||||
|
||||
// MaxOrganizationPageSize matches the largest page of the contract.
|
||||
const MaxOrganizationPageSize = 100
|
||||
|
||||
// OrganizationRepositories exposes the organization and membership
|
||||
// repositories. UnitOfWork binds them to one transaction, which a write
|
||||
// needs: an organization and its owner membership commit together.
|
||||
//
|
||||
// Tenant data of other aggregates, such as needs and invitations, refers to
|
||||
// organizations(id) with a restricting foreign key and always filters by the
|
||||
// organization taken from a membership, never from a body.
|
||||
type OrganizationRepositories interface {
|
||||
Organizations() OrganizationRepository
|
||||
Memberships() MembershipRepository
|
||||
}
|
||||
|
||||
// OrganizationRepository stores organizations. Every read and write names an
|
||||
// account, and only an active membership gives access, so a caller cannot
|
||||
// reach an organization through it without the membership that the
|
||||
// operations of the contract require.
|
||||
type OrganizationRepository interface {
|
||||
// CreateWithOwner stores a new organization and the active owner
|
||||
// membership of its creator. The two inserts run in the surrounding
|
||||
// transaction, so a failure between them leaves neither. The database also
|
||||
// refuses to commit an organization that has no active owner (constraint
|
||||
// organizations_owner_required, SQLSTATE 23514, raised by the commit of
|
||||
// the transaction), whatever code inserted it. owner must be an active
|
||||
// owner membership of organization; an unknown account fails with
|
||||
// ErrUserNotFound, and the caller's transaction is aborted.
|
||||
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
|
||||
|
||||
// GetForMember returns the organization with its representatives and the
|
||||
// active membership of the account in it, read from one snapshot in one
|
||||
// statement, so the profile and the list never come from two states. It
|
||||
// returns ErrOrganizationNotFound when the organization does not exist,
|
||||
// when the account has no membership in it, and when the membership is
|
||||
// suspended, removed, or left.
|
||||
GetForMember(ctx context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error)
|
||||
|
||||
// ListForUser returns one page of the organizations where the account has
|
||||
// an active membership, newest membership first.
|
||||
ListForUser(ctx context.Context, query OrganizationListQuery) (OrganizationPage, error)
|
||||
|
||||
// UpdateProfile stores the profile of organization as returned by
|
||||
// domain.Organization.ApplyProfile on behalf of the account actorID. It
|
||||
// applies only when the stored version still equals organization.Version()
|
||||
// and the actor has an active membership with a role that manages the
|
||||
// organization. The same statement advances the version by one, and the
|
||||
// representative list is replaced in the same transaction, so the returned
|
||||
// organization carries the new version. It never changes the verification
|
||||
// level.
|
||||
//
|
||||
// Lock order: the statement locks the organization row, then the actor's
|
||||
// membership row FOR SHARE, so a revocation committed while it waits stops
|
||||
// the write. Every writer of both tables, such as the member management,
|
||||
// must lock organizations first and memberships second, or two
|
||||
// transactions can deadlock.
|
||||
//
|
||||
// It returns ErrOrganizationNotFound for an unknown organization or an
|
||||
// actor without an active membership, ErrOrganizationManagerRequired for
|
||||
// an active member whose role cannot manage, and
|
||||
// ErrOrganizationVersionConflict for a stale version, checked in that
|
||||
// order. A failure leaves the organization unchanged.
|
||||
UpdateProfile(ctx context.Context, actorID uuid.UUID, organization domain.Organization) (domain.Organization, error)
|
||||
}
|
||||
|
||||
// MembershipRepository stores memberships. A membership is unique per account
|
||||
// and organization.
|
||||
type MembershipRepository interface {
|
||||
// Insert stores a membership. A second membership of the same account in
|
||||
// the same organization, in any state, returns an error wrapping
|
||||
// ErrMembershipExists; an unknown organization returns
|
||||
// ErrOrganizationNotFound and an unknown account ErrUserNotFound. The
|
||||
// database error aborts the surrounding transaction.
|
||||
Insert(ctx context.Context, membership domain.Membership) error
|
||||
|
||||
// Get returns the membership of the account in the organization in any
|
||||
// state, or ErrMembershipNotFound. The caller checks GrantsAccess before
|
||||
// it trusts the membership.
|
||||
Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error)
|
||||
}
|
||||
|
||||
// OrganizationListQuery selects one page of an account's organizations.
|
||||
type OrganizationListQuery struct {
|
||||
UserID uuid.UUID
|
||||
// After continues after the position of the last item of the previous
|
||||
// page; nil reads the first page.
|
||||
After *OrganizationListPosition
|
||||
// Limit is the page size, from 1 to MaxOrganizationPageSize.
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// OrganizationListPosition is the ordering key of an item in ListForUser.
|
||||
type OrganizationListPosition struct {
|
||||
JoinedAt time.Time
|
||||
OrganizationID uuid.UUID
|
||||
}
|
||||
|
||||
// MemberOrganization is an organization with the membership of the account
|
||||
// that listed it.
|
||||
type MemberOrganization struct {
|
||||
Organization domain.OrganizationSummary
|
||||
Membership domain.Membership
|
||||
}
|
||||
|
||||
// OrganizationPositionOf returns the ordering key of item for the next page.
|
||||
func OrganizationPositionOf(item MemberOrganization) OrganizationListPosition {
|
||||
return OrganizationListPosition{JoinedAt: item.Membership.CreatedAt(), OrganizationID: item.Organization.ID()}
|
||||
}
|
||||
|
||||
// OrganizationPage is one page of ListForUser.
|
||||
type OrganizationPage struct {
|
||||
Items []MemberOrganization
|
||||
// HasMore reports that another page follows; read it with After set to
|
||||
// the position of the last item.
|
||||
HasMore bool
|
||||
}
|
||||
@@ -50,6 +50,7 @@ type Transactor interface {
|
||||
type UnitOfWork interface {
|
||||
IdentityRepositories
|
||||
ConsentRepositories
|
||||
OrganizationRepositories
|
||||
Policies() PolicyRepository
|
||||
Deliveries() DeliveryRepository
|
||||
MailRequests() MailRequestRepository
|
||||
|
||||
+32
-6
@@ -416,7 +416,7 @@ backend/
|
||||
cmd/app/main.go calls bootstrap.Run and reports errors
|
||||
config/ shared runtime configuration
|
||||
internal/
|
||||
domain/ flat package; DomainEvent, identity types, consent ledger, product policy
|
||||
domain/ flat package; DomainEvent, identity types, consent ledger, organizations and memberships, product policy
|
||||
usecase/health/ operational readiness usecase
|
||||
port/inbound/ readiness and event handler input boundaries
|
||||
usecase/identity/ password validation before hashing (Credentials)
|
||||
@@ -425,7 +425,7 @@ backend/
|
||||
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
|
||||
usecase/notification/ mail requests and the consumer that stores them as deliveries
|
||||
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, policy, password hashing, and mail boundaries
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ request metrics
|
||||
@@ -438,7 +438,7 @@ backend/
|
||||
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
|
||||
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
|
||||
ml/api/ generated client from backend/codegen/ogen-ml.yml
|
||||
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, and policy repositories, health check
|
||||
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ cache adapter and Redis check
|
||||
seaweedfs/ S3 adapter and bucket check
|
||||
@@ -448,12 +448,12 @@ backend/
|
||||
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
|
||||
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
|
||||
bootstrap/ configuration, wiring, lifecycle, shutdown
|
||||
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, and consent ledger tables
|
||||
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, consent ledger, and organization tables
|
||||
codegen/ ogen and sqlc configs
|
||||
pkg/testutil/ fake application clock shared by tests
|
||||
```
|
||||
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
|
||||
Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
@@ -469,7 +469,7 @@ This is a compact map, not a claim that every planned product package exists. Cu
|
||||
| --- | --- | --- |
|
||||
| identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities |
|
||||
| candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions |
|
||||
| company | Company and its members | companies, company_members |
|
||||
| company | Company and its members | organizations, organization_representatives, memberships |
|
||||
| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history |
|
||||
| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items |
|
||||
| invitation | Offer and contact permission | invitations, invitation_events, contact_grants |
|
||||
@@ -637,6 +637,32 @@ Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/`
|
||||
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201).
|
||||
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet.
|
||||
|
||||
### Organizations and memberships
|
||||
|
||||
Implemented as storage, ports, and a source contract (TASK-077): migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers (TASK-078) and the server-side context and membership checks of every tenant operation (TASK-079) are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints.
|
||||
|
||||
Tables:
|
||||
|
||||
- `organizations`: UUIDv7 `id` (the `org_id` of every organization path), `name` (1-200 characters, the bound of the consent snapshot), `description`, `sphere` (free text; the PRD has no taxonomy), four public contact columns (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), the verification columns `verification_level`, `verification_basis`, and `verification_changed_at`, the profile `version`, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters, `https` website without credentials).
|
||||
- `organization_representatives`: `organization_id`, `ordinal` (0 to 9, so at most ten), `name`, and `job_title`; deleted with the organization row. The list is replaced as a whole with a profile update.
|
||||
- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state`, and the times. `UNIQUE (user_id, organization_id)` allows one membership per pair in any state, and `UNIQUE (organization_id, id)` is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys are `ON DELETE RESTRICT`.
|
||||
|
||||
Decisions:
|
||||
|
||||
- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The decision follows TASK-079 (the context comes only from the caller's active memberships, and a terminated membership closes reads at once) and TASK-085 (a switch clears the client's tenant queries).
|
||||
- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it (TASK-081, TASK-082). `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing (TASK-083, TASK-463).
|
||||
- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; TASK-086 adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (TASK-087 reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier).
|
||||
- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management (TASK-084), not of this constraint, which would otherwise block a platform decision about an abusive organization.
|
||||
- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management of TASK-084, which changes a membership and the organization together, and the tenant repository of TASK-079 must take the locks in that order, or two transactions can deadlock.
|
||||
- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the ledger tests of TASK-062 and TASK-063 to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records (TASK-198), together with the keys of needs (TASK-179). All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3).
|
||||
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` (TASK-078) keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (TASK-078 and TASK-087 need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations).
|
||||
|
||||
What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction):
|
||||
|
||||
- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction.
|
||||
- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above.
|
||||
- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet.
|
||||
|
||||
## Frontend
|
||||
|
||||
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
|
||||
|
||||
@@ -275,6 +275,31 @@ Unit tests (`make -C backend test`) cover the ledger rules without a database:
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the revocation usecase, the HTTP handler, or the call of the consent usecase from registration and the invitation acceptance, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically.
|
||||
|
||||
## Organization tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the organization rules without a database:
|
||||
|
||||
- `internal/domain/` (`organization_test.go`, `membership_test.go`): a profile accepts a name only and a complete card; every rule names the field that breaks it by a JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`) without quoting the value: an empty, padded, multi-line, over-long, or non-UTF-8 name, a description or sphere with a line break or control character, a website that is not `https` or has credentials, a port, an IP address, a numeric or hexadecimal host, or no dot, an email without a domain dot, a phone outside E.164, a Telegram username without `@`, and eleven representatives. CRLF in a description is stored as LF. `NewOrganization` starts at version 1 with a UUIDv7 and the level `e0` on `confirmed_email`, whatever the profile looks like; `ApplyProfile` keeps the identifier, the version, and the verification and never moves the update time backwards; a level pairs only with its own bases; `e0` to `e2` map to the quota tiers of the policy and `e3` has none; a stored row that was changed outside the application fails to restore. The card holds the profile and the level only. A representative is redacted in `fmt` and `slog` output, also inside an enclosing struct, and an organization logs only its identifier, version, and level. Only the owner manages the company, only an `active` membership gives access, the four roles and four states are the contract values, and `NewMembership` refuses a nil identifier, an unknown role, and a zero time.
|
||||
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): organization constraint errors map to their sentinels by SQLSTATE and constraint name without the failing row, which holds representative names; other errors keep only the SQLSTATE and the constraint; a deadlock maps to `ErrTransactionConflict`; invalid input fails before any statement; the manager roles passed to SQL come from the domain rule.
|
||||
- `internal/adapter/primary/http/` (`organization_test.go`): under a session the operations answer 501 after validation and 400 with the pointer for each rule of the schema (a name over 200 characters or with a line break, a missing `expected_version`, contacts that omit a field, an http website or one with credentials, a phone outside E.164, a Telegram username without `@`, eleven representatives, a representative with a contact, null `name`, `contacts`, or `representatives`, a limit over 100, an identifier that is not a UUID); the representatives of the candidate card may be absent, null, or empty, and a card without contacts is refused. Each of eleven fields that would carry a right or a trust level (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`) is refused alone on create and on update with the whole-body pointer. Under `DenyAllSecurity` all four operations answer 401, with or without a cookie and with a `user_id` parameter. The request DTOs have exactly the profile fields and no role, owner, member, or verification field, the card has no membership, role, basis, or time, the list takes only the page, an absent list differs from an empty one in `OrganizationUpdate`, every documented example decodes and validates, and the bundle has closed request objects, the CSRF scheme on both writes, the Idempotency-Key on create, 412 on update, and no operation that sets a level or a role.
|
||||
- `frontend/src/shared/api/organization-contract.test.ts`: the generated Zod schemas accept a name only and a complete card for create and update, require `expected_version`, accept null only for `description` and `sphere`, refuse the same limits as the contract, drop a role or a verification level that a client adds, list the four levels, roles, and states, and, at the type level, give the requests no role, owner, member, verification, or identity field, the card no membership or basis, and the membership no account.
|
||||
|
||||
`TestOrganizationsAndMemberships` in `backend/integration_test/organizations_test.go` uses `bootstrap(t, postgresService)` with the migrated schema and truncates the organization tables with `users` between cases:
|
||||
|
||||
- Storage: an organization is stored with its owner and read back with its profile, representatives in order, version 1, the level `e0`, and the active owner membership; fields that are not set are NULL.
|
||||
- Membership uniqueness: a repeated membership of the same account and organization, in each of the four roles and after the member left, fails with `ErrMembershipExists` naming `memberships_user_id_organization_id_key`, a raw insert fails with SQLSTATE 23505, and only one row remains; another account or organization is another pair.
|
||||
- Atomic creation: an unknown owner account rolls back the organization, its representatives, and the membership; a later failure of the same transaction does too; an owner membership that is a recruiter, belongs to another organization, or is zero is refused before any write.
|
||||
- Owner at commit: a transaction that inserts an organization alone, with a recruiter only, with a suspended owner only, or with an owner that it moves to `removed` before it commits fails at commit with SQLSTATE 23514 on `organizations_owner_required` and leaves nothing; an organization and an active owner inserted in one transaction commit.
|
||||
- Scoped list: the organizations of one account include the ones where it is a recruiter and exclude those where its membership is suspended, left, or removed and every organization of another account; pages of two follow the same order with no gap or repeat; memberships created at the same instant order by the organization identifier; invalid queries, including a position without an organization identifier, are refused; an organization without representatives reads back with an empty list.
|
||||
- Access: an account that is no member, an unknown account, an unknown organization, and a `suspended`, `removed`, or `left` member all get `ErrOrganizationNotFound`, a restored member reads again, and `Memberships().Get` returns the stored state in any state.
|
||||
- Update: the owner replaces the profile, the representative list, and the contacts, the version advances to 2 and the update time changes, cleared fields become NULL, and a verification level that a process set to `e1` is still `e1` after the next profile update. A recruiter gets `ErrOrganizationManagerRequired`, a suspended owner, an outsider, and an unknown account get `ErrOrganizationNotFound` even with a stale version, a stale version gets `ErrOrganizationVersionConflict`, and none of them changes the stored organization.
|
||||
- Revocation during an update: a transaction that revokes the second owner stays open, an update by that owner queues behind its membership lock (seen in `pg_stat_activity`), and when the revocation commits the update returns `ErrOrganizationNotFound` and writes nothing. Without `FOR SHARE` on the actor's membership the test fails.
|
||||
- Concurrency: eight updates from the same version on their own connections give exactly one success and seven conflicts, and the stored name and representative belong to the same winner.
|
||||
- Constraints through raw SQL: an empty, padded, multi-line, or over-long name, an unknown level, a basis of another level, version zero, a description with a padded end or a control character, a sphere with a line break, an http website or one with credentials, an email with a space, a phone without `+`, a Telegram username without `@`, an update before the creation time, the level and basis pairs of `e1`, `e2`, and `e3` (the right ones accepted, the wrong ones refused), a composite foreign key onto `(organization_id, id)` of the memberships (accepted for the member's own organization, refused for another), an unknown role (including `manager`), an unknown state (including `invited`), an eleventh representative, and a padded job title are refused by constraint name; the organizations table has no column for a role, an owner, a member, or a user.
|
||||
- Deletion: an account with a membership and an organization with a member cannot be deleted (SQLSTATE 23001); once the memberships are gone, the organization takes its representatives with it.
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. The suite does not cover the usecases, the handlers, the session and CSRF mapping, or the claim that the contract is enforced end to end, because none of them exists yet; the atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
|
||||
|
||||
## Future software validation
|
||||
|
||||
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
|
||||
|
||||
+32
-6
@@ -416,7 +416,7 @@ backend/
|
||||
cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
|
||||
config/ общая конфигурация runtime
|
||||
internal/
|
||||
domain/ плоский пакет; DomainEvent, типы identity, журнал согласий, продуктовая политика
|
||||
domain/ плоский пакет; DomainEvent, типы identity, журнал согласий, организации и членства, продуктовая политика
|
||||
usecase/health/ operational readiness usecase
|
||||
port/inbound/ inbound границы readiness и обработчиков событий
|
||||
usecase/identity/ проверка пароля до хеширования (Credentials)
|
||||
@@ -425,7 +425,7 @@ backend/
|
||||
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
|
||||
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки
|
||||
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, политики, хеширования паролей и почты
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ метрики запросов
|
||||
@@ -438,7 +438,7 @@ backend/
|
||||
mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала
|
||||
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
|
||||
ml/api/ generated client из backend/codegen/ogen-ml.yml
|
||||
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий и политики, health check
|
||||
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ адаптер кеша и проверка Redis
|
||||
seaweedfs/ S3-адаптер и проверка bucket
|
||||
@@ -448,12 +448,12 @@ backend/
|
||||
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
|
||||
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
|
||||
bootstrap/ конфигурация, wiring, lifecycle, shutdown
|
||||
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты, заданий по сроку и журнала согласий
|
||||
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты, заданий по сроку, журнала согласий и организаций
|
||||
codegen/ конфигурация ogen и sqlc
|
||||
pkg/testutil/ fake clock приложения, общий для тестов
|
||||
```
|
||||
|
||||
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
|
||||
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Типы организации, проверки и членства лежат в `organization.go` и `membership.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
|
||||
|
||||
`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
|
||||
|
||||
@@ -469,7 +469,7 @@ backend/
|
||||
| --- | --- | --- |
|
||||
| identity | Email, подтверждение, сессии и роли | users, email_tokens, sessions, external_identities |
|
||||
| candidate | Профиль, контакты, согласия и видимость | profiles, contacts, skills, consents, resume_versions |
|
||||
| company | Компания и ее сотрудники | companies, company_members |
|
||||
| company | Компания и ее сотрудники | organizations, organization_representatives, memberships |
|
||||
| assessment | Опрос, задания, попытки, оценка и грейд | questionnaires, task_templates, attempts, answers, grade_history |
|
||||
| matching | Потребности, фильтры, ранжирование и версии подборок | hiring_needs, search_runs, search_items |
|
||||
| invitation | Предложение и право раскрыть контакты | invitations, invitation_events, contact_grants |
|
||||
@@ -637,6 +637,32 @@ contact_grant относится к паре кандидат-компания
|
||||
- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201).
|
||||
- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет.
|
||||
|
||||
### Организации и членства
|
||||
|
||||
Реализовано как хранение, порты и исходный контракт (TASK-077): миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками (TASK-078) и серверные проверки контекста и членства для каждой tenant-операции (TASK-079) запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения.
|
||||
|
||||
Таблицы:
|
||||
|
||||
- `organizations`: UUIDv7 `id` (это `org_id` каждого пути организации), `name` (1-200 символов, граница снимка в согласии), `description`, `sphere` (свободный текст; таксономии в PRD нет), четыре столбца публичных контактов (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), столбцы проверки `verification_level`, `verification_basis` и `verification_changed_at`, `version` профиля и времена. Каждый текстовый столбец имеет CHECK с тем же форматом и границами, что и контракт (без пробелов и управляющих символов по краям, сайт по `https` без учетных данных).
|
||||
- `organization_representatives`: `organization_id`, `ordinal` (от 0 до 9, то есть не более десяти), `name` и `job_title`; удаляется вместе со строкой организации. Список заменяется целиком при обновлении профиля.
|
||||
- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state` и времена. `UNIQUE (user_id, organization_id)` допускает одно членство на пару в любом состоянии, а `UNIQUE (organization_id, id)` - цель составных внешних ключей, которыми поздние таблицы (назначения потребностей) привязывают членство к его организации. Оба внешних ключа - `ON DELETE RESTRICT`.
|
||||
|
||||
Решения:
|
||||
|
||||
- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Решение следует TASK-079 (контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение) и TASK-085 (переключение очищает клиентские запросы с областью организации).
|
||||
- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает (TASK-081, TASK-082). В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают (TASK-083, TASK-463).
|
||||
- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (ступень читает TASK-087 и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет).
|
||||
- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками (TASK-084), а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации.
|
||||
- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками TASK-084, которое меняет членство и организацию вместе, и tenant-репозиторий TASK-079 обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться.
|
||||
- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала TASK-062 и TASK-063 создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений (TASK-198), вместе с ключами потребностей (TASK-179). Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD).
|
||||
- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` (TASK-078) держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (TASK-078 и TASK-087 нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации).
|
||||
|
||||
Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции):
|
||||
|
||||
- `Organizations().CreateWithOwner` сохраняет организацию и членство владельца и проверяет, что владелец - активное членство `owner` именно этой организации. Неизвестный аккаунт возвращает `ErrUserNotFound` и прерывает внешнюю транзакцию.
|
||||
- `GetForMember` читает организацию, ее представителей (собранных в JSON тем же оператором) и активное членство вызывающего из одного снимка и возвращает их либо `ErrOrganizationNotFound` одинаково для неизвестной организации, аккаунта без членства и участника в состоянии `suspended`, `removed` или `left`. `ListForUser` постранично отдает активные организации одного аккаунта от нового членства к старому с идентификатором организации как разрешением ничьей. `UpdateProfile` описан выше.
|
||||
- `Memberships().Insert` возвращает `ErrMembershipExists` для повторной пары в любом состоянии, `ErrOrganizationNotFound` для неизвестной организации и `ErrUserNotFound` для неизвестного аккаунта; `Get` возвращает членство в любом состоянии или `ErrMembershipNotFound`, а вызывающий проверяет `GrantsAccess`. Метода, который меняет роль или состояние, пока нет.
|
||||
|
||||
## Frontend
|
||||
|
||||
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
|
||||
|
||||
@@ -275,6 +275,31 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase отзыва, HTTP-обработчик и вызов usecase согласий из регистрации и принятия приглашения, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно.
|
||||
|
||||
## Тесты организаций
|
||||
|
||||
Модульные тесты (`make -C backend test`) проверяют правила организаций без базы данных:
|
||||
|
||||
- `internal/domain/` (`organization_test.go`, `membership_test.go`): профиль принимает только название и полную карточку; каждое правило называет поле, которое его нарушает, указателем JSON Pointer (`/name`, `/contacts/website`, `/representatives/1/name`), не цитируя значение: пустое, с пробелами по краям, многострочное, слишком длинное или не UTF-8 название, описание или сфера с переводом строки или управляющим символом, сайт не по `https`, с учетными данными, портом, IP-адресом, числовым или шестнадцатеричным хостом или без точки, email без точки в домене, телефон вне E.164, имя Telegram без `@` и одиннадцать представителей. CRLF в описании сохраняется как LF. `NewOrganization` начинает с версии 1, UUIDv7 и уровня `e0` на основании `confirmed_email`, как бы ни выглядел профиль; `ApplyProfile` сохраняет идентификатор, версию и проверку и никогда не двигает время обновления назад; уровень сочетается только со своими основаниями; `e0`-`e2` сопоставляются ступеням квот политики, а у `e3` ступени нет; сохраненная строка, измененная вне приложения, не восстанавливается. Карточка содержит только профиль и уровень. Представитель скрыт в выводе `fmt` и `slog`, в том числе внутри объемлющей структуры, а организация логирует только идентификатор, версию и уровень. Компанией управляет только владелец, доступ дает только `active` членство, четыре роли и четыре состояния совпадают со значениями контракта, а `NewMembership` отказывает на nil-идентификатор, неизвестную роль и нулевое время.
|
||||
- `internal/adapter/secondary/postgres/` (`organizations_test.go`): ошибки ограничений организаций сопоставляются своим sentinel по SQLSTATE и имени ограничения без строки с ошибкой, в которой лежат имена представителей; остальные ошибки хранят только SQLSTATE и ограничение; взаимная блокировка сопоставляется `ErrTransactionConflict`; некорректный ввод отвергается до любого оператора; управляющие роли, передаваемые в SQL, берутся из доменного правила.
|
||||
- `internal/adapter/primary/http/` (`organization_test.go`): при наличии сессии операции отвечают 501 после валидации и 400 с указателем на каждое правило схемы (название длиннее 200 символов или с переводом строки, отсутствующий `expected_version`, контакты без одного поля, сайт по http или с учетными данными, телефон вне E.164, имя Telegram без `@`, одиннадцать представителей, представитель с контактом, null в `name`, `contacts` или `representatives`, лимит больше 100, идентификатор не UUID); представители карточки кандидата могут отсутствовать, быть null или пустыми, а карточка без контактов отвергается. Каждое из одиннадцати полей, которые несли бы право или уровень доверия (`role`, `owner_id`, `verification_level`, `verification`, `verification_basis`, `members`, `membership`, `candidate_card`, `id`, `version`, `created_at`), отвергается по отдельности при создании и обновлении с указателем на все тело. Под `DenyAllSecurity` все четыре операции отвечают 401 с cookie и без и с параметром `user_id`. DTO запросов содержат ровно поля профиля и не содержат поля роли, владельца, участника или проверки, в карточке нет членства, роли, основания и времени, список принимает только страницу, в `OrganizationUpdate` отсутствующий список отличается от пустого, каждый документированный пример декодируется и проходит валидацию, а в bundle запросы - закрытые объекты, обе записи требуют схему CSRF, создание требует Idempotency-Key, обновление объявляет 412, и нет операции, которая задает уровень или роль.
|
||||
- `frontend/src/shared/api/organization-contract.test.ts`: сгенерированные схемы Zod принимают только название и полную карточку для создания и обновления, требуют `expected_version`, допускают null только для `description` и `sphere`, отвергают те же пределы, что и контракт, отбрасывают роль или уровень проверки, добавленные клиентом, перечисляют четыре уровня, роли и состояния и, на уровне типов, не дают запросам полей роли, владельца, участника, проверки или идентичности, карточке - членства и основания, а членству - аккаунта.
|
||||
|
||||
`TestOrganizationsAndMemberships` в `backend/integration_test/organizations_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой и между случаями очищает таблицы организаций вместе с `users`:
|
||||
|
||||
- Хранение: организация сохраняется с владельцем и читается с профилем, представителями по порядку, версией 1, уровнем `e0` и активным членством владельца; незаданные поля равны NULL.
|
||||
- Уникальность членства: повторное членство того же аккаунта в той же организации, в каждой из четырех ролей и после выхода участника, завершается `ErrMembershipExists` с именем `memberships_user_id_organization_id_key`, прямая вставка завершается SQLSTATE 23505, и остается одна строка; другой аккаунт или другая организация - другая пара.
|
||||
- Атомарное создание: неизвестный аккаунт владельца откатывает организацию, представителей и членство; последующий сбой той же транзакции тоже; членство владельца, которое является рекрутером, относится к другой организации или нулевое, отвергается до любой записи.
|
||||
- Владелец при фиксации: транзакция, вставляющая только организацию, только с рекрутером, только с приостановленным владельцем или с владельцем, которого она переводит в `removed` до фиксации, падает при фиксации с SQLSTATE 23514 на `organizations_owner_required` и ничего не оставляет; организация и активный владелец, вставленные в одной транзакции, фиксируются.
|
||||
- Список в своей области: организации одного аккаунта включают те, где он рекрутер, и исключают те, где его членство приостановлено, завершено выходом или удалено, и все организации другого аккаунта; страницы по две следуют одному порядку без пропуска и повтора; членства, созданные в один момент, упорядочиваются по идентификатору организации; некорректные запросы, в том числе позиция без идентификатора организации, отвергаются; организация без представителей читается с пустым списком.
|
||||
- Доступ: аккаунт без членства, неизвестный аккаунт, неизвестная организация и участник в состоянии `suspended`, `removed` или `left` получают `ErrOrganizationNotFound`, восстановленный участник снова читает, а `Memberships().Get` возвращает сохраненное состояние в любом состоянии.
|
||||
- Обновление: владелец заменяет профиль, список представителей и контакты, версия растет до 2, время обновления меняется, очищенные поля становятся NULL, а уровень проверки, который процесс выставил в `e1`, остается `e1` после следующего обновления профиля. Рекрутер получает `ErrOrganizationManagerRequired`, приостановленный владелец, посторонний и неизвестный аккаунт получают `ErrOrganizationNotFound` даже с устаревшей версией, устаревшая версия получает `ErrOrganizationVersionConflict`, и ничто из этого не меняет сохраненную организацию.
|
||||
- Отзыв во время обновления: транзакция, отзывающая второго владельца, остается открытой, обновление этого владельца встает в очередь за блокировкой его членства (видно в `pg_stat_activity`), а когда отзыв фиксируется, обновление возвращает `ErrOrganizationNotFound` и ничего не пишет. Без `FOR SHARE` на членстве исполнителя тест падает.
|
||||
- Конкуренция: восемь обновлений от одной версии на своих соединениях дают ровно один успех и семь конфликтов, а сохраненные название и представитель принадлежат одному победителю.
|
||||
- Ограничения через прямой SQL: пустое, с пробелами по краям, многострочное или слишком длинное название, неизвестный уровень, основание другого уровня, версия ноль, описание с пробелом на конце или управляющим символом, сфера с переводом строки, сайт по http или с учетными данными, email с пробелом, телефон без `+`, имя Telegram без `@`, обновление раньше создания, пары уровня и основания для `e1`, `e2` и `e3` (верные принимаются, неверные отвергаются), составной внешний ключ на `(organization_id, id)` членств (принимается для организации самого участника, отвергается для чужой), неизвестная роль (включая `manager`), неизвестное состояние (включая `invited`), одиннадцатый представитель и должность с пробелом по краю отвергаются по имени ограничения; в таблице организаций нет столбца роли, владельца, участника или пользователя.
|
||||
- Удаление: аккаунт с членством и организацию с участником удалить нельзя (SQLSTATE 23001); когда членства удалены, организация забирает представителей с собой.
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Набор не покрывает usecase, обработчики, сопоставление сессии и CSRF и утверждение, что контракт соблюдается сквозным путем, потому что ничего из этого еще нет; атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
@@ -6,4 +6,5 @@ export { getHealthMock } from './health/health.msw'
|
||||
export { getIdentityMock } from './identity/identity.msw'
|
||||
export { getInvitationMock } from './invitation/invitation.msw'
|
||||
export { getNeedMock } from './need/need.msw'
|
||||
export { getOrganizationMock } from './organization/organization.msw'
|
||||
export { getSupportMock } from './support/support.msw'
|
||||
@@ -6,4 +6,5 @@ export * from './health/health';
|
||||
export * from './identity/identity';
|
||||
export * from './invitation/invitation';
|
||||
export * from './need/need';
|
||||
export * from './organization/organization';
|
||||
export * from './support/support';
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
faker
|
||||
} from '@faker-js/faker';
|
||||
|
||||
import {
|
||||
fakeFromPattern
|
||||
} from '../../mock-pattern';
|
||||
|
||||
import {
|
||||
HttpResponse,
|
||||
http
|
||||
} from 'msw';
|
||||
import type {
|
||||
RequestHandlerOptions
|
||||
} from 'msw';
|
||||
|
||||
import type {
|
||||
MyOrganizationList,
|
||||
Organization
|
||||
} from '../../schemas';
|
||||
|
||||
|
||||
export const getListMyOrganizationsResponseMock = (overrideResponse: Partial<Extract<MyOrganizationList, object>> = {}): MyOrganizationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({organization: {id: faker.string.uuid(), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), verification_level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const)}, membership: {organization_id: faker.string.uuid(), role: faker.helpers.arrayElement(['owner','recruiter','hiring_manager','technical_expert'] as const), state: faker.helpers.arrayElement(['active','suspended','removed','left'] as const), joined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
export const getCreateOrganizationResponseMock = (overrideResponse: Partial<Extract<Organization, object>> = {}): Organization => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), verification: {level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const), basis: faker.helpers.arrayElement(['confirmed_email','corporate_domain','requisites_and_authority','manual_review','partner_status'] as const), changed_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, candidate_card: {id: faker.string.uuid(), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), null]), verification_level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
export const getGetOrganizationResponseMock = (overrideResponse: Partial<Extract<Organization, object>> = {}): Organization => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), verification: {level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const), basis: faker.helpers.arrayElement(['confirmed_email','corporate_domain','requisites_and_authority','manual_review','partner_status'] as const), changed_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, candidate_card: {id: faker.string.uuid(), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), null]), verification_level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
export const getUpdateOrganizationResponseMock = (overrideResponse: Partial<Extract<Organization, object>> = {}): Organization => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), verification: {level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const), basis: faker.helpers.arrayElement(['confirmed_email','corporate_domain','requisites_and_authority','manual_review','partner_status'] as const), changed_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, candidate_card: {id: faker.string.uuid(), name: fakeFromPattern("^\\S(?:[^\\n\\r]*\\S)?$", {minLength: 1, maxLength: 200}), description: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 2000}}),null,]), sphere: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), contacts: {website: faker.helpers.arrayElement([fakeFromPattern("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$", {minLength: 9, maxLength: 300}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,])}, representatives: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), job_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})})), null]), verification_level: faker.helpers.arrayElement(['e0','e1','e2','e3'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
|
||||
export const getListMyOrganizationsMockHandler = (overrideResponse?: MyOrganizationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<MyOrganizationList> | MyOrganizationList), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/organizations', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getListMyOrganizationsResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getCreateOrganizationMockHandler = (overrideResponse?: Organization | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<Organization> | Organization), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/organizations', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getCreateOrganizationResponseMock(),
|
||||
{ status: 201
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getGetOrganizationMockHandler = (overrideResponse?: Organization | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<Organization> | Organization), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/organizations/:orgId', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getGetOrganizationResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getUpdateOrganizationMockHandler = (overrideResponse?: Organization | ((info: Parameters<Parameters<typeof http.patch>[1]>[0]) => Promise<Organization> | Organization), options?: RequestHandlerOptions) => {
|
||||
return http.patch('*/api/v1/organizations/:orgId', async (info: Parameters<Parameters<typeof http.patch>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getUpdateOrganizationResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
export const getOrganizationMock = () => [
|
||||
getListMyOrganizationsMockHandler(),
|
||||
getCreateOrganizationMockHandler(),
|
||||
getGetOrganizationMockHandler(),
|
||||
getUpdateOrganizationMockHandler()
|
||||
]
|
||||
@@ -0,0 +1,471 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
useMutation,
|
||||
useQuery
|
||||
} from '@tanstack/react-query';
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type {
|
||||
CreateOrganizationHeaders,
|
||||
ListMyOrganizationsParams,
|
||||
MyOrganizationList,
|
||||
Organization,
|
||||
OrganizationCreate,
|
||||
OrganizationUpdate,
|
||||
Problem
|
||||
} from '../../schemas';
|
||||
|
||||
import { apiRequest } from '../../client';
|
||||
import type { ErrorType } from '../../client';
|
||||
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
|
||||
|
||||
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
|
||||
const result = { queryKey } as T & { queryKey: K };
|
||||
for (const key of Object.keys(query)) {
|
||||
// The explicit queryKey always wins, matching the previous
|
||||
// `{ ...query, queryKey }` spread where it was set last.
|
||||
if (key === 'queryKey') continue;
|
||||
Object.defineProperty(result, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: () => (query as Record<string, unknown>)[key],
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const getListMyOrganizationsUrl = (params?: ListMyOrganizationsParams,) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? 'null' : String(value))
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0 ? `/api/v1/me/organizations?${stringifiedParams}` : `/api/v1/me/organizations`
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @summary List the organizations available to the current account.
|
||||
*/
|
||||
export const listMyOrganizations = async (params?: ListMyOrganizationsParams, options?: Parameters<typeof apiRequest>[1]): Promise<MyOrganizationList> => {
|
||||
|
||||
return apiRequest<MyOrganizationList>(getListMyOrganizationsUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getListMyOrganizationsQueryKey = (params?: ListMyOrganizationsParams,) => {
|
||||
return [
|
||||
`/api/v1/me/organizations`, ...(params ? [params] : [])
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getListMyOrganizationsQueryOptions = <TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListMyOrganizationsQueryKey(params);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMyOrganizations>>> = ({ signal }) => listMyOrganizations(params, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type ListMyOrganizationsQueryResult = NonNullable<Awaited<ReturnType<typeof listMyOrganizations>>>
|
||||
export type ListMyOrganizationsQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
|
||||
params: undefined | ListMyOrganizationsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyOrganizations>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyOrganizations>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyOrganizations>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyOrganizations>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary List the organizations available to the current account.
|
||||
*/
|
||||
|
||||
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getListMyOrganizationsQueryOptions(params,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getCreateOrganizationUrl = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/organizations`
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @summary Create an organization; the caller becomes its owner.
|
||||
*/
|
||||
export const createOrganization = async (organizationCreate: OrganizationCreate,
|
||||
headers: CreateOrganizationHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
if (!h) return {};
|
||||
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
||||
if (Symbol.iterator in h) {
|
||||
return Object.fromEntries(
|
||||
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<Organization>(getCreateOrganizationUrl(),
|
||||
{
|
||||
...options,
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
|
||||
body: JSON.stringify(organizationCreate)
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getCreateOrganizationMutationKey = () => ['createOrganization'] as const;
|
||||
|
||||
export const getCreateOrganizationMutationOptions = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext> => {
|
||||
|
||||
const mutationKey = getCreateOrganizationMutationKey();
|
||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
||||
options
|
||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
||||
: {mutation: { mutationKey, }, request: undefined};
|
||||
|
||||
|
||||
|
||||
|
||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof createOrganization>>, CreateOrganizationMutationVariables> = (props) => {
|
||||
const {data,headers} = props ?? {};
|
||||
|
||||
return createOrganization(data,headers,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type CreateOrganizationMutationResult = NonNullable<Awaited<ReturnType<typeof createOrganization>>>
|
||||
export type CreateOrganizationMutationBody = OrganizationCreate
|
||||
export type CreateOrganizationMutationError = ErrorType<Problem>
|
||||
export type CreateOrganizationMutationVariables = {data: OrganizationCreate;headers: CreateOrganizationHeaders}
|
||||
|
||||
/**
|
||||
* @summary Create an organization; the caller becomes its owner.
|
||||
*/
|
||||
export const useCreateOrganization = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof createOrganization>>,
|
||||
TError,
|
||||
CreateOrganizationMutationVariables,
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getCreateOrganizationMutationOptions(options), queryClient);
|
||||
}
|
||||
export const getGetOrganizationUrl = (orgId: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/organizations/${orgId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @summary Read an organization of which the caller is a member.
|
||||
*/
|
||||
export const getOrganization = async (orgId: string, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
|
||||
|
||||
return apiRequest<Organization>(getGetOrganizationUrl(orgId),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetOrganizationQueryKey = (orgId: string,) => {
|
||||
return [
|
||||
`/api/v1/organizations/${orgId}`
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getGetOrganizationQueryOptions = <TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetOrganizationQueryKey(orgId);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getOrganization>>> = ({ signal }) => getOrganization(orgId, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type GetOrganizationQueryResult = NonNullable<Awaited<ReturnType<typeof getOrganization>>>
|
||||
export type GetOrganizationQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
|
||||
orgId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganization>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganization>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
|
||||
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganization>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganization>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
|
||||
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary Read an organization of which the caller is a member.
|
||||
*/
|
||||
|
||||
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
|
||||
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getGetOrganizationQueryOptions(orgId,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getUpdateOrganizationUrl = (orgId: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/organizations/${orgId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @summary Change the profile of an organization.
|
||||
*/
|
||||
export const updateOrganization = async (orgId: string,
|
||||
organizationUpdate: OrganizationUpdate, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
if (!h) return {};
|
||||
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
||||
if (Symbol.iterator in h) {
|
||||
return Object.fromEntries(
|
||||
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<Organization>(getUpdateOrganizationUrl(orgId),
|
||||
{
|
||||
...options,
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) },
|
||||
body: JSON.stringify(organizationUpdate)
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getUpdateOrganizationMutationKey = () => ['updateOrganization'] as const;
|
||||
|
||||
export const getUpdateOrganizationMutationOptions = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext> => {
|
||||
|
||||
const mutationKey = getUpdateOrganizationMutationKey();
|
||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
||||
options
|
||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
||||
: {mutation: { mutationKey, }, request: undefined};
|
||||
|
||||
|
||||
|
||||
|
||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof updateOrganization>>, UpdateOrganizationMutationVariables> = (props) => {
|
||||
const {orgId,data} = props ?? {};
|
||||
|
||||
return updateOrganization(orgId,data,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type UpdateOrganizationMutationResult = NonNullable<Awaited<ReturnType<typeof updateOrganization>>>
|
||||
export type UpdateOrganizationMutationBody = OrganizationUpdate
|
||||
export type UpdateOrganizationMutationError = ErrorType<Problem>
|
||||
export type UpdateOrganizationMutationVariables = {orgId: string;data: OrganizationUpdate}
|
||||
|
||||
/**
|
||||
* @summary Change the profile of an organization.
|
||||
*/
|
||||
export const useUpdateOrganization = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof updateOrganization>>,
|
||||
TError,
|
||||
UpdateOrganizationMutationVariables,
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getUpdateOrganizationMutationOptions(options), queryClient);
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import { describe, expect, expectTypeOf, it } from "vitest";
|
||||
import { createOrganization, updateOrganization } from "./endpoints/organization/organization";
|
||||
import {
|
||||
CreateOrganizationBody,
|
||||
ListMyOrganizationsParams,
|
||||
MyOrganizationList,
|
||||
Organization,
|
||||
OrganizationCreate,
|
||||
OrganizationMembership,
|
||||
CandidateOrganizationCard,
|
||||
OrganizationRole,
|
||||
OrganizationUpdate,
|
||||
OrganizationVerificationLevel,
|
||||
UpdateOrganizationBody,
|
||||
} from "./schemas";
|
||||
|
||||
// These tests pin the generated organization contract that the employer
|
||||
// cabinet (TASK-080) and the organization switcher consume. They fail when
|
||||
// regeneration drops a limit of the profile, loses a level, role, or state of
|
||||
// the PRD, lets a request carry a role or a verification level, or lets a
|
||||
// response name a member or an account.
|
||||
|
||||
const contacts = {
|
||||
website: "https://payments.example.com",
|
||||
email: "careers@payments.example.com",
|
||||
phone: "+74950000000",
|
||||
telegram: "@payments_careers",
|
||||
} as const;
|
||||
|
||||
const noContacts = { website: null, email: null, phone: null, telegram: null } as const;
|
||||
|
||||
const representative = { name: "Анна Тестова", job_title: "Руководитель по подбору" } as const;
|
||||
|
||||
const organizationId = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01";
|
||||
|
||||
const card = {
|
||||
id: organizationId,
|
||||
name: "ООО Пример Платежи",
|
||||
description: "Платежный сервис для малого бизнеса.",
|
||||
sphere: "Платежи и финансовые сервисы",
|
||||
contacts,
|
||||
representatives: [representative],
|
||||
verification_level: "e0",
|
||||
} as const;
|
||||
|
||||
const organization = {
|
||||
id: organizationId,
|
||||
version: 2,
|
||||
name: card.name,
|
||||
description: card.description,
|
||||
sphere: card.sphere,
|
||||
contacts,
|
||||
representatives: [representative],
|
||||
verification: { level: "e0", basis: "confirmed_email", changed_at: "2026-10-06T09:00:00Z" },
|
||||
candidate_card: card,
|
||||
created_at: "2026-10-06T09:00:00Z",
|
||||
updated_at: "2026-10-06T09:40:00Z",
|
||||
} as const;
|
||||
|
||||
const createSchemas = [
|
||||
["OrganizationCreate", OrganizationCreate],
|
||||
["CreateOrganizationBody", CreateOrganizationBody],
|
||||
] as const;
|
||||
|
||||
describe.each(createSchemas)("generated %s", (_name, schema) => {
|
||||
it("accepts a name only and a complete card", () => {
|
||||
expect(schema.parse({ name: "ООО Пример" })).toEqual({ name: "ООО Пример" });
|
||||
const complete = {
|
||||
name: card.name,
|
||||
description: card.description,
|
||||
sphere: card.sphere,
|
||||
contacts,
|
||||
representatives: [representative],
|
||||
};
|
||||
expect(schema.parse(complete)).toEqual(complete);
|
||||
});
|
||||
|
||||
it("requires the name", () => {
|
||||
expect(schema.safeParse({ sphere: "Платежи" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an empty name", { name: "" }],
|
||||
["a name over 200 characters", { name: "я".repeat(201) }],
|
||||
["a name with a leading space", { name: " ООО" }],
|
||||
["a name with a line break", { name: "ООО\nПример" }],
|
||||
["an empty description", { name: "ООО", description: "" }],
|
||||
["a description over 2000 characters", { name: "ООО", description: "я".repeat(2001) }],
|
||||
["a sphere with a trailing space", { name: "ООО", sphere: "Платежи " }],
|
||||
["a sphere over 100 characters", { name: "ООО", sphere: "я".repeat(101) }],
|
||||
[
|
||||
"an http website",
|
||||
{ name: "ООО", contacts: { ...noContacts, website: "http://a.example.com" } },
|
||||
],
|
||||
[
|
||||
"a website with credentials",
|
||||
{ name: "ООО", contacts: { ...noContacts, website: "https://user@a.example.com" } },
|
||||
],
|
||||
["a phone outside E.164", { name: "ООО", contacts: { ...noContacts, phone: "8 495 000" } }],
|
||||
[
|
||||
"a Telegram username without @",
|
||||
{ name: "ООО", contacts: { ...noContacts, telegram: "careers" } },
|
||||
],
|
||||
[
|
||||
"an email that is not an address",
|
||||
{ name: "ООО", contacts: { ...noContacts, email: "careers" } },
|
||||
],
|
||||
[
|
||||
"contacts that omit a field",
|
||||
{ name: "ООО", contacts: { website: null, email: null, phone: null } },
|
||||
],
|
||||
[
|
||||
"eleven representatives",
|
||||
{ name: "ООО", representatives: Array.from({ length: 11 }, () => representative) },
|
||||
],
|
||||
[
|
||||
"a representative without a job title",
|
||||
{ name: "ООО", representatives: [{ name: "Анна Тестова" }] },
|
||||
],
|
||||
])("rejects %s", (_case, body) => {
|
||||
expect(schema.safeParse(body).success).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a role or a verification level that a client would add", () => {
|
||||
// Generated Zod strips unknown keys and the server rejects them with 400,
|
||||
// so a value sent this way never reaches the profile.
|
||||
const parsed = schema.parse({
|
||||
name: "ООО Пример",
|
||||
role: "owner",
|
||||
verification_level: "e3",
|
||||
owner_id: "01928f7a-0000-7000-8000-00000000c0de",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({ name: "ООО Пример" });
|
||||
});
|
||||
});
|
||||
|
||||
const updateSchemas = [
|
||||
["OrganizationUpdate", OrganizationUpdate],
|
||||
["UpdateOrganizationBody", UpdateOrganizationBody],
|
||||
] as const;
|
||||
|
||||
describe.each(updateSchemas)("generated %s", (_name, schema) => {
|
||||
it("requires the version that the client read", () => {
|
||||
expect(schema.safeParse({ name: "ООО Новое" }).success).toBe(false);
|
||||
expect(schema.safeParse({ expected_version: 0, name: "ООО Новое" }).success).toBe(false);
|
||||
expect(schema.parse({ expected_version: 1 })).toEqual({ expected_version: 1 });
|
||||
});
|
||||
|
||||
it("replaces the profile fields as a whole and clears the optional ones with null", () => {
|
||||
const body = {
|
||||
expected_version: 3,
|
||||
name: "ООО Новое",
|
||||
description: null,
|
||||
sphere: null,
|
||||
contacts: noContacts,
|
||||
representatives: [],
|
||||
};
|
||||
|
||||
expect(schema.parse(body)).toEqual(body);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a null name", { name: null }],
|
||||
["null contacts", { contacts: null }],
|
||||
["null representatives", { representatives: null }],
|
||||
["partial contacts", { contacts: { website: null, email: null } }],
|
||||
["a name with a line break", { name: "ООО\nНовое" }],
|
||||
])("rejects %s", (_case, change) => {
|
||||
expect(schema.safeParse({ expected_version: 1, ...change }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a role or a verification level that a client would add", () => {
|
||||
const parsed = schema.parse({
|
||||
expected_version: 1,
|
||||
name: "ООО Новое",
|
||||
role: "owner",
|
||||
verification: { level: "e3", basis: "manual_review", changed_at: "2026-10-06T09:00:00Z" },
|
||||
verification_level: "e2",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({ expected_version: 1, name: "ООО Новое" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated Organization", () => {
|
||||
it("accepts a member's view with the level e0 and the candidate card", () => {
|
||||
expect(Organization.parse(organization)).toEqual(organization);
|
||||
});
|
||||
|
||||
it("accepts an organization without a description, a sphere, or contacts", () => {
|
||||
const bare = {
|
||||
...organization,
|
||||
description: null,
|
||||
sphere: null,
|
||||
contacts: noContacts,
|
||||
representatives: [],
|
||||
candidate_card: {
|
||||
...card,
|
||||
description: null,
|
||||
sphere: null,
|
||||
contacts: noContacts,
|
||||
representatives: [],
|
||||
},
|
||||
};
|
||||
|
||||
expect(Organization.parse(bare)).toEqual(bare);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an unknown level", { verification: { ...organization.verification, level: "e4" } }],
|
||||
["an unknown basis", { verification: { ...organization.verification, basis: "domain" } }],
|
||||
["a version below 1", { version: 0 }],
|
||||
["a missing card", { candidate_card: undefined }],
|
||||
])("rejects %s", (_case, change) => {
|
||||
expect(Organization.safeParse({ ...organization, ...change }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a candidate card whose representatives are not published", () => {
|
||||
const withoutList: Record<string, unknown> = { ...card };
|
||||
delete withoutList["representatives"];
|
||||
|
||||
expect(CandidateOrganizationCard.parse(withoutList)).toEqual(withoutList);
|
||||
expect(
|
||||
CandidateOrganizationCard.parse({ ...card, representatives: null }).representatives,
|
||||
).toBeNull();
|
||||
expect(
|
||||
CandidateOrganizationCard.safeParse({ ...card, representatives: undefined }).success,
|
||||
).toBe(true);
|
||||
expect(CandidateOrganizationCard.safeParse({ ...card, contacts: undefined }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("knows the four levels of the PRD and no others", () => {
|
||||
expect(OrganizationVerificationLevel.options).toEqual(["e0", "e1", "e2", "e3"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated roles and memberships", () => {
|
||||
it("lists the four roles of the FR07 matrix", () => {
|
||||
expect(OrganizationRole.options).toEqual([
|
||||
"owner",
|
||||
"recruiter",
|
||||
"hiring_manager",
|
||||
"technical_expert",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an unknown role", { role: "admin" }],
|
||||
["an unknown state", { state: "invited" }],
|
||||
])("rejects a membership with %s", (_case, change) => {
|
||||
const membership = {
|
||||
organization_id: organizationId,
|
||||
role: "owner",
|
||||
state: "active",
|
||||
joined_at: "2026-10-06T09:00:00Z",
|
||||
...change,
|
||||
};
|
||||
|
||||
expect(OrganizationMembership.safeParse(membership).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated MyOrganizationList", () => {
|
||||
const page = {
|
||||
items: [
|
||||
{
|
||||
organization: { id: organizationId, name: card.name, verification_level: "e0" },
|
||||
membership: {
|
||||
organization_id: organizationId,
|
||||
role: "owner",
|
||||
state: "active",
|
||||
joined_at: "2026-10-06T09:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
} as const;
|
||||
|
||||
it("accepts the organizations of the caller with the caller's membership", () => {
|
||||
expect(MyOrganizationList.parse(page)).toEqual(page);
|
||||
});
|
||||
|
||||
it("accepts the page parameters and nothing that names another account", () => {
|
||||
expect(ListMyOrganizationsParams.parse({ limit: 50 })).toEqual({ limit: 50 });
|
||||
expect(ListMyOrganizationsParams.parse({})).toEqual({ limit: 20 });
|
||||
expect(ListMyOrganizationsParams.safeParse({ limit: 101 }).success).toBe(false);
|
||||
expect(
|
||||
ListMyOrganizationsParams.parse({ user_id: "01928f7a-0000-7000-8000-00000000c0de" }),
|
||||
).toEqual({
|
||||
limit: 20,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
type RaisingRequestKey =
|
||||
| "role"
|
||||
| "roles"
|
||||
| "verification"
|
||||
| "verification_level"
|
||||
| "verification_basis"
|
||||
| "level"
|
||||
| "basis"
|
||||
| "trust_level"
|
||||
| "owner"
|
||||
| "owner_id"
|
||||
| "members"
|
||||
| "membership"
|
||||
| "user_id"
|
||||
| "account_id"
|
||||
| "permissions"
|
||||
| "candidate_card"
|
||||
| "id"
|
||||
| "version"
|
||||
| "created_at"
|
||||
| "updated_at";
|
||||
|
||||
type PrivateCardKey =
|
||||
| "role"
|
||||
| "membership"
|
||||
| "members"
|
||||
| "verification"
|
||||
| "basis"
|
||||
| "version"
|
||||
| "created_at"
|
||||
| "updated_at"
|
||||
| "user_id"
|
||||
| "account_id";
|
||||
|
||||
it("exposes request DTOs without a role, an owner, a verification level, or a member", () => {
|
||||
expectTypeOf<Extract<keyof OrganizationCreate, RaisingRequestKey>>().toEqualTypeOf<never>();
|
||||
expectTypeOf<Extract<keyof OrganizationUpdate, RaisingRequestKey>>().toEqualTypeOf<never>();
|
||||
expectTypeOf<keyof OrganizationCreate>().toEqualTypeOf<
|
||||
"name" | "description" | "sphere" | "contacts" | "representatives"
|
||||
>();
|
||||
expectTypeOf<keyof OrganizationUpdate>().toEqualTypeOf<
|
||||
"expected_version" | "name" | "description" | "sphere" | "contacts" | "representatives"
|
||||
>();
|
||||
expectTypeOf<
|
||||
Extract<keyof NonNullable<OrganizationUpdate["contacts"]>, RaisingRequestKey>
|
||||
>().toEqualTypeOf<never>();
|
||||
// A representative is presentation only: a name and a job title, no
|
||||
// account, no role, and no contact.
|
||||
expectTypeOf<keyof NonNullable<OrganizationUpdate["representatives"]>[number]>().toEqualTypeOf<
|
||||
"name" | "job_title"
|
||||
>();
|
||||
expectTypeOf(createOrganization).parameter(0).toEqualTypeOf<OrganizationCreate>();
|
||||
expectTypeOf(updateOrganization).parameter(1).toEqualTypeOf<OrganizationUpdate>();
|
||||
});
|
||||
|
||||
it("keeps the role in the membership and off the organization and its card", () => {
|
||||
expectTypeOf<
|
||||
Extract<keyof Organization, "role" | "members" | "membership" | "owner_id">
|
||||
>().toEqualTypeOf<never>();
|
||||
expectTypeOf<Extract<keyof CandidateOrganizationCard, PrivateCardKey>>().toEqualTypeOf<never>();
|
||||
expectTypeOf<
|
||||
Extract<keyof OrganizationMembership, "user_id" | "account_id" | "email">
|
||||
>().toEqualTypeOf<never>();
|
||||
expectTypeOf<OrganizationMembership["role"]>().toEqualTypeOf<
|
||||
"owner" | "recruiter" | "hiring_manager" | "technical_expert"
|
||||
>();
|
||||
expectTypeOf<OrganizationMembership["state"]>().toEqualTypeOf<
|
||||
"active" | "suspended" | "removed" | "left"
|
||||
>();
|
||||
expectTypeOf<Organization["verification"]["level"]>().toEqualTypeOf<"e0" | "e1" | "e2" | "e3">();
|
||||
expectTypeOf<keyof ListMyOrganizationsParams>().toEqualTypeOf<"limit" | "cursor">();
|
||||
});
|
||||
File renamed without changes.
File renamed without changes.
@@ -7,6 +7,8 @@
|
||||
|
||||
export * from './consentTextVersion.zod';
|
||||
export * from './contactFieldKind.zod';
|
||||
export * from './contactPhoneNumber.zod';
|
||||
export * from './contactTelegramUsername.zod';
|
||||
export * from './currencyCode.zod';
|
||||
export * from './emailAddress.zod';
|
||||
export * from './gradeCode.zod';
|
||||
@@ -36,4 +38,5 @@ export * from './health';
|
||||
export * from './identity';
|
||||
export * from './invitation';
|
||||
export * from './need';
|
||||
export * from './organization';
|
||||
export * from './support';
|
||||
@@ -89,7 +89,7 @@ export const CandidateInvitation = zod.object({
|
||||
"organization": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(candidateInvitationOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
|
||||
}).describe('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.'),
|
||||
}).describe('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.'),
|
||||
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
|
||||
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
|
||||
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
|
||||
|
||||
@@ -37,7 +37,7 @@ export const CandidateInvitationList = zod.object({
|
||||
"organization": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(candidateInvitationListItemsItemOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
|
||||
}).describe('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.'),
|
||||
}).describe('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.'),
|
||||
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
|
||||
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
|
||||
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
|
||||
|
||||
@@ -30,7 +30,7 @@ export const CandidateInvitationSummary = zod.object({
|
||||
"organization": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(candidateInvitationSummaryOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
|
||||
}).describe('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.'),
|
||||
}).describe('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.'),
|
||||
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
|
||||
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
|
||||
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
|
||||
|
||||
@@ -21,9 +21,7 @@ export * from './contactDisclosure.zod';
|
||||
export * from './contactFullName.zod';
|
||||
export * from './contactGrant.zod';
|
||||
export * from './contactGrantState.zod';
|
||||
export * from './contactPhoneNumber.zod';
|
||||
export * from './contactRevocationReason.zod';
|
||||
export * from './contactTelegramUsername.zod';
|
||||
export * from './createOrganizationInvitationBody.zod';
|
||||
export * from './createOrganizationInvitationHeaders.zod';
|
||||
export * from './declineMyInvitationBody.zod';
|
||||
|
||||
@@ -12,7 +12,7 @@ export const invitationOrganizationNameMax = 200;
|
||||
export const InvitationOrganization = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(invitationOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
|
||||
}).describe('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.')
|
||||
}).describe('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.')
|
||||
|
||||
export type InvitationOrganization = zod.input<typeof InvitationOrganization>;
|
||||
export type InvitationOrganizationOutput = zod.output<typeof InvitationOrganization>;
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const candidateOrganizationCardNameMax = 200;
|
||||
|
||||
|
||||
export const candidateOrganizationCardNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const candidateOrganizationCardDescriptionOneMax = 2000;
|
||||
|
||||
export const candidateOrganizationCardSphereOneMax = 100;
|
||||
|
||||
|
||||
export const candidateOrganizationCardSphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const candidateOrganizationCardContactsWebsiteOneMin = 9;
|
||||
export const candidateOrganizationCardContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const candidateOrganizationCardContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const candidateOrganizationCardContactsEmailOneMin = 3;
|
||||
export const candidateOrganizationCardContactsEmailOneMax = 254;
|
||||
|
||||
export const candidateOrganizationCardContactsPhoneOneMin = 8;
|
||||
export const candidateOrganizationCardContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const candidateOrganizationCardContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const candidateOrganizationCardContactsTelegramOneMin = 6;
|
||||
export const candidateOrganizationCardContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const candidateOrganizationCardContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const candidateOrganizationCardRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const candidateOrganizationCardRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const candidateOrganizationCardRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const candidateOrganizationCardRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const candidateOrganizationCardRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const CandidateOrganizationCard = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(candidateOrganizationCardNameMax).regex(candidateOrganizationCardNameRegExp).describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(candidateOrganizationCardDescriptionOneMax).describe('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.'),zod.null()]).describe('Description of the organization, or null.'),
|
||||
"sphere": zod.union([zod.string().min(1).max(candidateOrganizationCardSphereOneMax).regex(candidateOrganizationCardSphereOneRegExp).describe('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.'),zod.null()]).describe('Field of business of the organization, or null.'),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(candidateOrganizationCardContactsWebsiteOneMin).max(candidateOrganizationCardContactsWebsiteOneMax).regex(candidateOrganizationCardContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(candidateOrganizationCardContactsEmailOneMin).max(candidateOrganizationCardContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(candidateOrganizationCardContactsPhoneOneMin).max(candidateOrganizationCardContactsPhoneOneMax).regex(candidateOrganizationCardContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(candidateOrganizationCardContactsTelegramOneMin).max(candidateOrganizationCardContactsTelegramOneMax).regex(candidateOrganizationCardContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(candidateOrganizationCardRepresentativesItemNameMax).regex(candidateOrganizationCardRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(candidateOrganizationCardRepresentativesItemJobTitleMax).regex(candidateOrganizationCardRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(candidateOrganizationCardRepresentativesMax).nullish().describe('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.'),
|
||||
"verification_level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
}).describe('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.')
|
||||
|
||||
export type CandidateOrganizationCard = zod.input<typeof CandidateOrganizationCard>;
|
||||
export type CandidateOrganizationCardOutput = zod.output<typeof CandidateOrganizationCard>;
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const createOrganizationBodyNameMax = 200;
|
||||
|
||||
|
||||
export const createOrganizationBodyNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const createOrganizationBodyDescriptionOneMax = 2000;
|
||||
|
||||
export const createOrganizationBodySphereOneMax = 100;
|
||||
|
||||
|
||||
export const createOrganizationBodySphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const createOrganizationBodyContactsWebsiteOneMin = 9;
|
||||
export const createOrganizationBodyContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const createOrganizationBodyContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const createOrganizationBodyContactsEmailOneMin = 3;
|
||||
export const createOrganizationBodyContactsEmailOneMax = 254;
|
||||
|
||||
export const createOrganizationBodyContactsPhoneOneMin = 8;
|
||||
export const createOrganizationBodyContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const createOrganizationBodyContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const createOrganizationBodyContactsTelegramOneMin = 6;
|
||||
export const createOrganizationBodyContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const createOrganizationBodyContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const createOrganizationBodyRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const createOrganizationBodyRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const createOrganizationBodyRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const createOrganizationBodyRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const createOrganizationBodyRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const CreateOrganizationBody = zod.object({
|
||||
"name": zod.string().min(1).max(createOrganizationBodyNameMax).regex(createOrganizationBodyNameRegExp).describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(createOrganizationBodyDescriptionOneMax).describe('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.'),zod.null()]).exactOptional(),
|
||||
"sphere": zod.union([zod.string().min(1).max(createOrganizationBodySphereOneMax).regex(createOrganizationBodySphereOneRegExp).describe('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.'),zod.null()]).exactOptional(),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(createOrganizationBodyContactsWebsiteOneMin).max(createOrganizationBodyContactsWebsiteOneMax).regex(createOrganizationBodyContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(createOrganizationBodyContactsEmailOneMin).max(createOrganizationBodyContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(createOrganizationBodyContactsPhoneOneMin).max(createOrganizationBodyContactsPhoneOneMax).regex(createOrganizationBodyContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(createOrganizationBodyContactsTelegramOneMin).max(createOrganizationBodyContactsTelegramOneMax).regex(createOrganizationBodyContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).exactOptional().describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(createOrganizationBodyRepresentativesItemNameMax).regex(createOrganizationBodyRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(createOrganizationBodyRepresentativesItemJobTitleMax).regex(createOrganizationBodyRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(createOrganizationBodyRepresentativesMax).exactOptional()
|
||||
}).describe('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.')
|
||||
|
||||
export type CreateOrganizationBody = zod.input<typeof CreateOrganizationBody>;
|
||||
export type CreateOrganizationBodyOutput = zod.output<typeof CreateOrganizationBody>;
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const createOrganizationHeadersIdempotencyKeyMax = 255;
|
||||
|
||||
|
||||
export const createOrganizationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
|
||||
|
||||
export const CreateOrganizationHeaders = zod.object({
|
||||
"Idempotency-Key": zod.string().min(1).max(createOrganizationHeadersIdempotencyKeyMax).regex(createOrganizationHeadersIdempotencyKeyRegExp)
|
||||
})
|
||||
|
||||
export type CreateOrganizationHeaders = zod.input<typeof CreateOrganizationHeaders>;
|
||||
export type CreateOrganizationHeadersOutput = zod.output<typeof CreateOrganizationHeaders>;
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export * from './candidateOrganizationCard.zod';
|
||||
export * from './createOrganizationBody.zod';
|
||||
export * from './createOrganizationHeaders.zod';
|
||||
export * from './listMyOrganizationsParams.zod';
|
||||
export * from './membershipState.zod';
|
||||
export * from './myOrganization.zod';
|
||||
export * from './myOrganizationList.zod';
|
||||
export * from './organization.zod';
|
||||
export * from './organizationContactChannels.zod';
|
||||
export * from './organizationCreate.zod';
|
||||
export * from './organizationDescription.zod';
|
||||
export * from './organizationMembership.zod';
|
||||
export * from './organizationName.zod';
|
||||
export * from './organizationRepresentative.zod';
|
||||
export * from './organizationRole.zod';
|
||||
export * from './organizationSphere.zod';
|
||||
export * from './organizationSummary.zod';
|
||||
export * from './organizationUpdate.zod';
|
||||
export * from './organizationVerification.zod';
|
||||
export * from './organizationVerificationBasis.zod';
|
||||
export * from './organizationVerificationLevel.zod';
|
||||
export * from './organizationVersion.zod';
|
||||
export * from './organizationWebsite.zod';
|
||||
export * from './updateOrganizationBody.zod';
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const listMyOrganizationsParamsLimitDefault = 20;
|
||||
export const listMyOrganizationsParamsLimitMax = 100;
|
||||
|
||||
export const listMyOrganizationsParamsCursorMax = 512;
|
||||
|
||||
|
||||
export const listMyOrganizationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const ListMyOrganizationsParams = zod.object({
|
||||
"limit": zod.int().min(1).max(listMyOrganizationsParamsLimitMax).default(listMyOrganizationsParamsLimitDefault),
|
||||
"cursor": zod.string().min(1).max(listMyOrganizationsParamsCursorMax).regex(listMyOrganizationsParamsCursorRegExp).exactOptional()
|
||||
})
|
||||
|
||||
export type ListMyOrganizationsParams = zod.input<typeof ListMyOrganizationsParams>;
|
||||
export type ListMyOrganizationsParamsOutput = zod.output<typeof ListMyOrganizationsParams>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const MembershipState = zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- 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.\n- left: the member ended the membership.\n\nOne 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.')
|
||||
|
||||
export type MembershipState = zod.input<typeof MembershipState>;
|
||||
export type MembershipStateOutput = zod.output<typeof MembershipState>;
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const myOrganizationOrganizationNameMax = 200;
|
||||
|
||||
|
||||
export const myOrganizationOrganizationNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
|
||||
export const MyOrganization = zod.object({
|
||||
"organization": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization, the `org_id` of its paths.'),
|
||||
"name": zod.string().min(1).max(myOrganizationOrganizationNameMax).regex(myOrganizationOrganizationNameRegExp).describe('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.'),
|
||||
"verification_level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
}).describe('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`.'),
|
||||
"membership": zod.object({
|
||||
"organization_id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('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.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn 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.'),
|
||||
"state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- 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.\n- left: the member ended the membership.\n\nOne 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.'),
|
||||
"joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('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).')
|
||||
}).describe('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.')
|
||||
}).describe('An organization available to the caller together with the caller\'s membership in it.')
|
||||
|
||||
export type MyOrganization = zod.input<typeof MyOrganization>;
|
||||
export type MyOrganizationOutput = zod.output<typeof MyOrganization>;
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const myOrganizationListItemsItemOrganizationNameMax = 200;
|
||||
|
||||
|
||||
export const myOrganizationListItemsItemOrganizationNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const myOrganizationListItemsMax = 100;
|
||||
|
||||
export const myOrganizationListPageNextCursorMax = 512;
|
||||
|
||||
|
||||
export const myOrganizationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const MyOrganizationList = zod.object({
|
||||
"items": zod.array(zod.object({
|
||||
"organization": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization, the `org_id` of its paths.'),
|
||||
"name": zod.string().min(1).max(myOrganizationListItemsItemOrganizationNameMax).regex(myOrganizationListItemsItemOrganizationNameRegExp).describe('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.'),
|
||||
"verification_level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
}).describe('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`.'),
|
||||
"membership": zod.object({
|
||||
"organization_id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('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.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn 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.'),
|
||||
"state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- 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.\n- left: the member ended the membership.\n\nOne 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.'),
|
||||
"joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('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).')
|
||||
}).describe('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.')
|
||||
}).describe('An organization available to the caller together with the caller\'s membership in it.')).max(myOrganizationListItemsMax).describe('Organizations of the page.'),
|
||||
"page": zod.object({
|
||||
"has_more": zod.boolean().describe('Whether another page follows this one.'),
|
||||
"next_cursor": zod.string().min(1).max(myOrganizationListPageNextCursorMax).regex(myOrganizationListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
|
||||
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
|
||||
}).describe('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.')
|
||||
|
||||
export type MyOrganizationList = zod.input<typeof MyOrganizationList>;
|
||||
export type MyOrganizationListOutput = zod.output<typeof MyOrganizationList>;
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
export const organizationNameMax = 200;
|
||||
|
||||
|
||||
export const organizationNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const organizationDescriptionOneMax = 2000;
|
||||
|
||||
export const organizationSphereOneMax = 100;
|
||||
|
||||
|
||||
export const organizationSphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationContactsWebsiteOneMin = 9;
|
||||
export const organizationContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const organizationContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const organizationContactsEmailOneMin = 3;
|
||||
export const organizationContactsEmailOneMax = 254;
|
||||
|
||||
export const organizationContactsPhoneOneMin = 8;
|
||||
export const organizationContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const organizationContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const organizationContactsTelegramOneMin = 6;
|
||||
export const organizationContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const organizationContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const organizationRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const organizationRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const organizationRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationRepresentativesMax = 10;
|
||||
|
||||
export const organizationCandidateCardNameMax = 200;
|
||||
|
||||
|
||||
export const organizationCandidateCardNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const organizationCandidateCardDescriptionOneMax = 2000;
|
||||
|
||||
export const organizationCandidateCardSphereOneMax = 100;
|
||||
|
||||
|
||||
export const organizationCandidateCardSphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCandidateCardContactsWebsiteOneMin = 9;
|
||||
export const organizationCandidateCardContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const organizationCandidateCardContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const organizationCandidateCardContactsEmailOneMin = 3;
|
||||
export const organizationCandidateCardContactsEmailOneMax = 254;
|
||||
|
||||
export const organizationCandidateCardContactsPhoneOneMin = 8;
|
||||
export const organizationCandidateCardContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const organizationCandidateCardContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const organizationCandidateCardContactsTelegramOneMin = 6;
|
||||
export const organizationCandidateCardContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const organizationCandidateCardContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const organizationCandidateCardRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const organizationCandidateCardRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCandidateCardRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const organizationCandidateCardRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCandidateCardRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const Organization = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization, the `org_id` of every organization-scoped path. It never changes.'),
|
||||
"version": zod.int().min(1).describe('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.'),
|
||||
"name": zod.string().min(1).max(organizationNameMax).regex(organizationNameRegExp).describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(organizationDescriptionOneMax).describe('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.'),zod.null()]).describe('Description of the organization, or null.'),
|
||||
"sphere": zod.union([zod.string().min(1).max(organizationSphereOneMax).regex(organizationSphereOneRegExp).describe('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.'),zod.null()]).describe('Field of business of the organization, or null.'),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(organizationContactsWebsiteOneMin).max(organizationContactsWebsiteOneMax).regex(organizationContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(organizationContactsEmailOneMin).max(organizationContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(organizationContactsPhoneOneMin).max(organizationContactsPhoneOneMax).regex(organizationContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(organizationContactsTelegramOneMin).max(organizationContactsTelegramOneMax).regex(organizationContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(organizationRepresentativesItemNameMax).regex(organizationRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(organizationRepresentativesItemJobTitleMax).regex(organizationRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(organizationRepresentativesMax).describe('Representatives in the order the owner gave them.'),
|
||||
"verification": zod.object({
|
||||
"level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.'),
|
||||
"basis": zod.enum(['confirmed_email', 'corporate_domain', 'requisites_and_authority', 'manual_review', 'partner_status']).describe('Ground of the current verification level, the reason a cabinet can show next to it.\n\n- confirmed_email: the confirmed email of the creating account (e0).\n- corporate_domain: a corporate email and a verified domain (e1).\n- requisites_and_authority: a check of the requisites and of the authority (e2).\n- manual_review: a manual check by the platform (e3).\n- partner_status: a partner status (e3).\n\nEach 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.'),
|
||||
"changed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the level was set to its current value; for a new organization, the creation time.')
|
||||
}).describe('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.'),
|
||||
"candidate_card": zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"name": zod.string().min(1).max(organizationCandidateCardNameMax).regex(organizationCandidateCardNameRegExp).describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(organizationCandidateCardDescriptionOneMax).describe('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.'),zod.null()]).describe('Description of the organization, or null.'),
|
||||
"sphere": zod.union([zod.string().min(1).max(organizationCandidateCardSphereOneMax).regex(organizationCandidateCardSphereOneRegExp).describe('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.'),zod.null()]).describe('Field of business of the organization, or null.'),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(organizationCandidateCardContactsWebsiteOneMin).max(organizationCandidateCardContactsWebsiteOneMax).regex(organizationCandidateCardContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(organizationCandidateCardContactsEmailOneMin).max(organizationCandidateCardContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(organizationCandidateCardContactsPhoneOneMin).max(organizationCandidateCardContactsPhoneOneMax).regex(organizationCandidateCardContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(organizationCandidateCardContactsTelegramOneMin).max(organizationCandidateCardContactsTelegramOneMax).regex(organizationCandidateCardContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(organizationCandidateCardRepresentativesItemNameMax).regex(organizationCandidateCardRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(organizationCandidateCardRepresentativesItemJobTitleMax).regex(organizationCandidateCardRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(organizationCandidateCardRepresentativesMax).nullish().describe('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.'),
|
||||
"verification_level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
}).describe('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.'),
|
||||
"created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
|
||||
"updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
}).describe('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.')
|
||||
|
||||
export type Organization = zod.input<typeof Organization>;
|
||||
export type OrganizationOutput = zod.output<typeof Organization>;
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationContactChannelsWebsiteOneMin = 9;
|
||||
export const organizationContactChannelsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const organizationContactChannelsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const organizationContactChannelsEmailOneMin = 3;
|
||||
export const organizationContactChannelsEmailOneMax = 254;
|
||||
|
||||
export const organizationContactChannelsPhoneOneMin = 8;
|
||||
export const organizationContactChannelsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const organizationContactChannelsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const organizationContactChannelsTelegramOneMin = 6;
|
||||
export const organizationContactChannelsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const organizationContactChannelsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
|
||||
export const OrganizationContactChannels = zod.object({
|
||||
"website": zod.union([zod.string().min(organizationContactChannelsWebsiteOneMin).max(organizationContactChannelsWebsiteOneMax).regex(organizationContactChannelsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(organizationContactChannelsEmailOneMin).max(organizationContactChannelsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(organizationContactChannelsPhoneOneMin).max(organizationContactChannelsPhoneOneMax).regex(organizationContactChannelsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(organizationContactChannelsTelegramOneMin).max(organizationContactChannelsTelegramOneMax).regex(organizationContactChannelsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationContactChannels = zod.input<typeof OrganizationContactChannels>;
|
||||
export type OrganizationContactChannelsOutput = zod.output<typeof OrganizationContactChannels>;
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationCreateNameMax = 200;
|
||||
|
||||
|
||||
export const organizationCreateNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const organizationCreateDescriptionOneMax = 2000;
|
||||
|
||||
export const organizationCreateSphereOneMax = 100;
|
||||
|
||||
|
||||
export const organizationCreateSphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCreateContactsWebsiteOneMin = 9;
|
||||
export const organizationCreateContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const organizationCreateContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const organizationCreateContactsEmailOneMin = 3;
|
||||
export const organizationCreateContactsEmailOneMax = 254;
|
||||
|
||||
export const organizationCreateContactsPhoneOneMin = 8;
|
||||
export const organizationCreateContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const organizationCreateContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const organizationCreateContactsTelegramOneMin = 6;
|
||||
export const organizationCreateContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const organizationCreateContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const organizationCreateRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const organizationCreateRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCreateRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const organizationCreateRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationCreateRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const OrganizationCreate = zod.object({
|
||||
"name": zod.string().min(1).max(organizationCreateNameMax).regex(organizationCreateNameRegExp).describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(organizationCreateDescriptionOneMax).describe('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.'),zod.null()]).exactOptional(),
|
||||
"sphere": zod.union([zod.string().min(1).max(organizationCreateSphereOneMax).regex(organizationCreateSphereOneRegExp).describe('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.'),zod.null()]).exactOptional(),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(organizationCreateContactsWebsiteOneMin).max(organizationCreateContactsWebsiteOneMax).regex(organizationCreateContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(organizationCreateContactsEmailOneMin).max(organizationCreateContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(organizationCreateContactsPhoneOneMin).max(organizationCreateContactsPhoneOneMax).regex(organizationCreateContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(organizationCreateContactsTelegramOneMin).max(organizationCreateContactsTelegramOneMax).regex(organizationCreateContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).exactOptional().describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(organizationCreateRepresentativesItemNameMax).regex(organizationCreateRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(organizationCreateRepresentativesItemJobTitleMax).regex(organizationCreateRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(organizationCreateRepresentativesMax).exactOptional()
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationCreate = zod.input<typeof OrganizationCreate>;
|
||||
export type OrganizationCreateOutput = zod.output<typeof OrganizationCreate>;
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationDescriptionMax = 2000;
|
||||
|
||||
|
||||
export const OrganizationDescription = zod.string().min(1).max(OrganizationDescriptionMax).describe('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.')
|
||||
|
||||
export type OrganizationDescription = zod.input<typeof OrganizationDescription>;
|
||||
export type OrganizationDescriptionOutput = zod.output<typeof OrganizationDescription>;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationMembership = zod.object({
|
||||
"organization_id": zod.uuid().describe('Identifier of the organization.'),
|
||||
"role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('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.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn 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.'),
|
||||
"state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- 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.\n- left: the member ended the membership.\n\nOne 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.'),
|
||||
"joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('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).')
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationMembership = zod.input<typeof OrganizationMembership>;
|
||||
export type OrganizationMembershipOutput = zod.output<typeof OrganizationMembership>;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationNameMax = 200;
|
||||
|
||||
|
||||
export const OrganizationNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
|
||||
export const OrganizationName = zod.string().min(1).max(OrganizationNameMax).regex(OrganizationNameRegExp).describe('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.')
|
||||
|
||||
export type OrganizationName = zod.input<typeof OrganizationName>;
|
||||
export type OrganizationNameOutput = zod.output<typeof OrganizationName>;
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationRepresentativeNameMax = 100;
|
||||
|
||||
|
||||
export const organizationRepresentativeNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationRepresentativeJobTitleMax = 100;
|
||||
|
||||
|
||||
export const organizationRepresentativeJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
|
||||
export const OrganizationRepresentative = zod.object({
|
||||
"name": zod.string().min(1).max(organizationRepresentativeNameMax).regex(organizationRepresentativeNameRegExp).describe('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": zod.string().min(1).max(organizationRepresentativeJobTitleMax).regex(organizationRepresentativeJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationRepresentative = zod.input<typeof OrganizationRepresentative>;
|
||||
export type OrganizationRepresentativeOutput = zod.output<typeof OrganizationRepresentative>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationRole = zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('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.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn 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.')
|
||||
|
||||
export type OrganizationRole = zod.input<typeof OrganizationRole>;
|
||||
export type OrganizationRoleOutput = zod.output<typeof OrganizationRole>;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationSphereMax = 100;
|
||||
|
||||
|
||||
export const OrganizationSphereRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
|
||||
export const OrganizationSphere = zod.string().min(1).max(OrganizationSphereMax).regex(OrganizationSphereRegExp).describe('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.')
|
||||
|
||||
export type OrganizationSphere = zod.input<typeof OrganizationSphere>;
|
||||
export type OrganizationSphereOutput = zod.output<typeof OrganizationSphere>;
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationSummaryNameMax = 200;
|
||||
|
||||
|
||||
export const organizationSummaryNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
|
||||
export const OrganizationSummary = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization, the `org_id` of its paths.'),
|
||||
"name": zod.string().min(1).max(organizationSummaryNameMax).regex(organizationSummaryNameRegExp).describe('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.'),
|
||||
"verification_level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
}).describe('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`.')
|
||||
|
||||
export type OrganizationSummary = zod.input<typeof OrganizationSummary>;
|
||||
export type OrganizationSummaryOutput = zod.output<typeof OrganizationSummary>;
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
export const organizationUpdateNameMax = 200;
|
||||
|
||||
|
||||
export const organizationUpdateNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const organizationUpdateDescriptionOneMax = 2000;
|
||||
|
||||
export const organizationUpdateSphereOneMax = 100;
|
||||
|
||||
|
||||
export const organizationUpdateSphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationUpdateContactsWebsiteOneMin = 9;
|
||||
export const organizationUpdateContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const organizationUpdateContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const organizationUpdateContactsEmailOneMin = 3;
|
||||
export const organizationUpdateContactsEmailOneMax = 254;
|
||||
|
||||
export const organizationUpdateContactsPhoneOneMin = 8;
|
||||
export const organizationUpdateContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const organizationUpdateContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const organizationUpdateContactsTelegramOneMin = 6;
|
||||
export const organizationUpdateContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const organizationUpdateContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const organizationUpdateRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const organizationUpdateRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationUpdateRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const organizationUpdateRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const organizationUpdateRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const OrganizationUpdate = zod.object({
|
||||
"expected_version": zod.int().min(1).describe('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.'),
|
||||
"name": zod.string().min(1).max(organizationUpdateNameMax).regex(organizationUpdateNameRegExp).exactOptional().describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(organizationUpdateDescriptionOneMax).describe('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.'),zod.null()]).exactOptional(),
|
||||
"sphere": zod.union([zod.string().min(1).max(organizationUpdateSphereOneMax).regex(organizationUpdateSphereOneRegExp).describe('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.'),zod.null()]).exactOptional(),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(organizationUpdateContactsWebsiteOneMin).max(organizationUpdateContactsWebsiteOneMax).regex(organizationUpdateContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(organizationUpdateContactsEmailOneMin).max(organizationUpdateContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(organizationUpdateContactsPhoneOneMin).max(organizationUpdateContactsPhoneOneMax).regex(organizationUpdateContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(organizationUpdateContactsTelegramOneMin).max(organizationUpdateContactsTelegramOneMax).regex(organizationUpdateContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).exactOptional().describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(organizationUpdateRepresentativesItemNameMax).regex(organizationUpdateRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(organizationUpdateRepresentativesItemJobTitleMax).regex(organizationUpdateRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(organizationUpdateRepresentativesMax).exactOptional()
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationUpdate = zod.input<typeof OrganizationUpdate>;
|
||||
export type OrganizationUpdateOutput = zod.output<typeof OrganizationUpdate>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationVerification = zod.object({
|
||||
"level": zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.'),
|
||||
"basis": zod.enum(['confirmed_email', 'corporate_domain', 'requisites_and_authority', 'manual_review', 'partner_status']).describe('Ground of the current verification level, the reason a cabinet can show next to it.\n\n- confirmed_email: the confirmed email of the creating account (e0).\n- corporate_domain: a corporate email and a verified domain (e1).\n- requisites_and_authority: a check of the requisites and of the authority (e2).\n- manual_review: a manual check by the platform (e3).\n- partner_status: a partner status (e3).\n\nEach 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.'),
|
||||
"changed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the level was set to its current value; for a new organization, the creation time.')
|
||||
}).describe('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.')
|
||||
|
||||
export type OrganizationVerification = zod.input<typeof OrganizationVerification>;
|
||||
export type OrganizationVerificationOutput = zod.output<typeof OrganizationVerification>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationVerificationBasis = zod.enum(['confirmed_email', 'corporate_domain', 'requisites_and_authority', 'manual_review', 'partner_status']).describe('Ground of the current verification level, the reason a cabinet can show next to it.\n\n- confirmed_email: the confirmed email of the creating account (e0).\n- corporate_domain: a corporate email and a verified domain (e1).\n- requisites_and_authority: a check of the requisites and of the authority (e2).\n- manual_review: a manual check by the platform (e3).\n- partner_status: a partner status (e3).\n\nEach 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.')
|
||||
|
||||
export type OrganizationVerificationBasis = zod.input<typeof OrganizationVerificationBasis>;
|
||||
export type OrganizationVerificationBasisOutput = zod.output<typeof OrganizationVerificationBasis>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationVerificationLevel = zod.enum(['e0', 'e1', 'e2', 'e3']).describe('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.\n\n- e0: the confirmed email of the account that created the organization. Every new organization starts here.\n- e1: a corporate email, a verified domain, and a link with the organization.\n- e2: a check of the requisites and of the authority of the person.\n- e3: a manual check or a partner status.\n\nThe 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.')
|
||||
|
||||
export type OrganizationVerificationLevel = zod.input<typeof OrganizationVerificationLevel>;
|
||||
export type OrganizationVerificationLevelOutput = zod.output<typeof OrganizationVerificationLevel>;
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
|
||||
export const OrganizationVersion = zod.int().min(1).describe('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.')
|
||||
|
||||
export type OrganizationVersion = zod.input<typeof OrganizationVersion>;
|
||||
export type OrganizationVersionOutput = zod.output<typeof OrganizationVersion>;
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const OrganizationWebsiteMin = 9;
|
||||
export const OrganizationWebsiteMax = 300;
|
||||
|
||||
|
||||
export const OrganizationWebsiteRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
|
||||
export const OrganizationWebsite = zod.string().min(OrganizationWebsiteMin).max(OrganizationWebsiteMax).regex(OrganizationWebsiteRegExp).describe('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.')
|
||||
|
||||
export type OrganizationWebsite = zod.input<typeof OrganizationWebsite>;
|
||||
export type OrganizationWebsiteOutput = zod.output<typeof OrganizationWebsite>;
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
export const updateOrganizationBodyNameMax = 200;
|
||||
|
||||
|
||||
export const updateOrganizationBodyNameRegExp = new RegExp('^\\S(?:[^\\n\\r]*\\S)?$');
|
||||
export const updateOrganizationBodyDescriptionOneMax = 2000;
|
||||
|
||||
export const updateOrganizationBodySphereOneMax = 100;
|
||||
|
||||
|
||||
export const updateOrganizationBodySphereOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const updateOrganizationBodyContactsWebsiteOneMin = 9;
|
||||
export const updateOrganizationBodyContactsWebsiteOneMax = 300;
|
||||
|
||||
|
||||
export const updateOrganizationBodyContactsWebsiteOneRegExp = new RegExp('^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$');
|
||||
export const updateOrganizationBodyContactsEmailOneMin = 3;
|
||||
export const updateOrganizationBodyContactsEmailOneMax = 254;
|
||||
|
||||
export const updateOrganizationBodyContactsPhoneOneMin = 8;
|
||||
export const updateOrganizationBodyContactsPhoneOneMax = 16;
|
||||
|
||||
|
||||
export const updateOrganizationBodyContactsPhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
|
||||
export const updateOrganizationBodyContactsTelegramOneMin = 6;
|
||||
export const updateOrganizationBodyContactsTelegramOneMax = 33;
|
||||
|
||||
|
||||
export const updateOrganizationBodyContactsTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
|
||||
export const updateOrganizationBodyRepresentativesItemNameMax = 100;
|
||||
|
||||
|
||||
export const updateOrganizationBodyRepresentativesItemNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const updateOrganizationBodyRepresentativesItemJobTitleMax = 100;
|
||||
|
||||
|
||||
export const updateOrganizationBodyRepresentativesItemJobTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
|
||||
export const updateOrganizationBodyRepresentativesMax = 10;
|
||||
|
||||
|
||||
export const UpdateOrganizationBody = zod.object({
|
||||
"expected_version": zod.int().min(1).describe('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.'),
|
||||
"name": zod.string().min(1).max(updateOrganizationBodyNameMax).regex(updateOrganizationBodyNameRegExp).exactOptional().describe('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.'),
|
||||
"description": zod.union([zod.string().min(1).max(updateOrganizationBodyDescriptionOneMax).describe('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.'),zod.null()]).exactOptional(),
|
||||
"sphere": zod.union([zod.string().min(1).max(updateOrganizationBodySphereOneMax).regex(updateOrganizationBodySphereOneRegExp).describe('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.'),zod.null()]).exactOptional(),
|
||||
"contacts": zod.object({
|
||||
"website": zod.union([zod.string().min(updateOrganizationBodyContactsWebsiteOneMin).max(updateOrganizationBodyContactsWebsiteOneMax).regex(updateOrganizationBodyContactsWebsiteOneRegExp).describe('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.'),zod.null()]),
|
||||
"email": zod.union([zod.email().min(updateOrganizationBodyContactsEmailOneMin).max(updateOrganizationBodyContactsEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]).describe('Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given.'),
|
||||
"phone": zod.union([zod.string().min(updateOrganizationBodyContactsPhoneOneMin).max(updateOrganizationBodyContactsPhoneOneMax).regex(updateOrganizationBodyContactsPhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]).describe('Public phone number of the organization, or null.'),
|
||||
"telegram": zod.union([zod.string().min(updateOrganizationBodyContactsTelegramOneMin).max(updateOrganizationBodyContactsTelegramOneMax).regex(updateOrganizationBodyContactsTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]).describe('Public Telegram account of the organization, or null.')
|
||||
}).exactOptional().describe('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.'),
|
||||
"representatives": zod.array(zod.object({
|
||||
"name": zod.string().min(1).max(updateOrganizationBodyRepresentativesItemNameMax).regex(updateOrganizationBodyRepresentativesItemNameRegExp).describe('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": zod.string().min(1).max(updateOrganizationBodyRepresentativesItemJobTitleMax).regex(updateOrganizationBodyRepresentativesItemJobTitleRegExp).describe('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.')
|
||||
}).describe('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.')).max(updateOrganizationBodyRepresentativesMax).exactOptional()
|
||||
}).describe('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.')
|
||||
|
||||
export type UpdateOrganizationBody = zod.input<typeof UpdateOrganizationBody>;
|
||||
export type UpdateOrganizationBodyOutput = zod.output<typeof UpdateOrganizationBody>;
|
||||
Reference in new issue
Block a user