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
+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, почта - тестовым адаптером.
|
||||
|
||||
Reference in new issue
Block a user