feat(invitations): send invitations into the candidate inbox atomically
This commit is contained in:
1 parent
fc35e27af5
commit
1a067221f7
46 files changed
+3276
-113
No files matched your search
+28
-10
@@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff
|
||||
|
||||
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
|
||||
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) works through the backend API; sending and the candidate side are not implemented (see [Invitation drafts](#invitation-drafts)). Other product workflows are not implemented: roles, profiles, assessments, grades, sending and answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks its notices; a sent invitation is the first product producer (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) and the send to the candidate's inbox with the candidate's list of invitations work through the backend API; the candidate's answers are not implemented (see [Invitation drafts](#invitation-drafts) and [Sending invitations](#sending-invitations)). Other product workflows are not implemented: roles, profiles, assessments, grades, answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
|
||||
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
|
||||
|
||||
@@ -412,22 +412,22 @@ Open points. Sending product notifications and the permission check they need ar
|
||||
|
||||
### Internal notifications
|
||||
|
||||
Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. No product module produces a notification yet. Invitations, the first planned producer, are not implemented, so the only event that reaches the inbox today is a synthetic one and a real recipient sees an empty list.
|
||||
Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. The send of an invitation is the first product producer ([Sending invitations](#sending-invitations)); the synthetic event remains for tests and probes.
|
||||
|
||||
Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications).
|
||||
|
||||
- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. When invitations arrive, the delivered state of an invitation is the existence of its inbox row.
|
||||
- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. The delivered state of an invitation is its own `delivered_at`, written by the send transaction; the inbox row of its notification follows through the consumer.
|
||||
- A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists.
|
||||
- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module therefore needs no change in the table, the consumer, or the API: it appends `invitation.delivered` and registers a content resolver for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. Until a resolver exists, an item of that source is listed without content.
|
||||
- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module needed no change in the table, the consumer, or the API: the send transaction appends `invitation.delivered` through `notification.InvitationNotifier`, and `notification.ResolveInvitationNotice` is registered for the source `invitation` in `notification.DefaultInboxSourceResolvers()`.
|
||||
- Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation.
|
||||
- Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `<CONSUMER_GROUP_PREFIX>.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored.
|
||||
- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The one resolver today belongs to the synthetic notice: its fixed Russian text names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. A candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet.
|
||||
- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The resolver of a delivered invitation reads it only when it is addressed to the recipient and delivered, in the organization of the entry, and names the organization and the role; it shows no candidate value and links to `/candidate/invitations`. The resolver of the synthetic notice uses a fixed Russian text that names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. Both read the name that way: a candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet.
|
||||
- Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction.
|
||||
- Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added.
|
||||
- Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds.
|
||||
- Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event.
|
||||
- Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)).
|
||||
- Not implemented: the invitation producer and its content resolver, an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application.
|
||||
- Not implemented: an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
@@ -941,13 +941,13 @@ The anonymous card for organizations is not built here: `AnonymousCardContent` i
|
||||
|
||||
### Invitation drafts
|
||||
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox row, no event, and no quota charge. Sending, withdrawal, the salary raise, the contact read, and every candidate operation of the invitation tag still answer 501 after the common checks. Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, and every candidate operation of the invitation tag except `ListMyInvitations` still answer 501 after the common checks. Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
|
||||
Tables:
|
||||
|
||||
- `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them.
|
||||
- `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction.
|
||||
- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created` or `draft_updated`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only.
|
||||
- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, or, since migration 00038, `delivered`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only.
|
||||
- `invitation_creation_results`: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier.
|
||||
|
||||
Decisions:
|
||||
@@ -962,12 +962,30 @@ Decisions:
|
||||
- Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked.
|
||||
- The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet.
|
||||
|
||||
How the later operations plug in: sending must resolve the candidate through the same visibility barrier again, because a draft keeps its candidate after a C2 revocation or a hiding, and then moves the draft to `delivered` by one UPDATE of `state`, `delivered_at`, `response_deadline_at`, and `version`, appends an audit event for that version, and writes the `invitation.delivered` outbox event whose inbox resolver for the source `invitation` is the existing plug-in point of [Internal notifications](#internal-notifications); the candidate's inbox reads `invitations` by `candidate_id` and `delivered_at`, and the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation.
|
||||
How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation.
|
||||
|
||||
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the quota charge and the limit of pending invitations per need, the sending, the raise, the withdrawal, the candidate side, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
|
||||
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the limit of pending invitations per need, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
|
||||
|
||||
Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL.
|
||||
|
||||
### Sending invitations
|
||||
|
||||
Implemented: `SendOrganizationInvitation` and the candidate's list of invitations `ListMyInvitations` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_delivery.go`, `usecase/invitation/send.go` and `candidate_inbox.go`, `usecase/notification/invitation.go`, the HTTP handler `adapter/primary/http/v1/invitation.go` with the cursor in `invitation_cursor.go`, the adapter `adapter/secondary/postgres/invitation_delivery.go` with `db/queries/invitation_delivery.sql`, the wiring in `bootstrap/invitation.go`, and migration `00038_send_invitations.sql`.
|
||||
|
||||
- One transaction. A send takes the organization lock (`CompanyQuotaRepository.LockOrganization`), the owner check of the membership, the Idempotency-Key, and the invitation row lock, in the order of every invitation command, and then the locks of the visible cohort. It runs the visibility barrier of the card read again, spends one invitation of the organization quota, moves the draft to `delivered` with one conditional UPDATE (`state`, `version` plus one, `delivered_at`, `response_deadline_at`, `updated_at`; the terms version stays), appends the audit event `delivered`, and writes the outbox events: `invitation.delivered` for the in-platform notification and `notification.mail_requested` with its `mail_requests` row for the email. The internal sending step is never stored: when the answer arrives, the invitation is `delivered`, it is in the candidate's list, and the charge is recorded. A failure of any step rolls everything back.
|
||||
- The candidate's inbox entry is the delivered invitation itself. `ListMyInvitations` reads the rows with the candidate of the session and a `delivered_at`, newest first by `(delivered_at, id)` over the partial index of migration 00037, with the current name of the sending organization; a draft has no delivery and is never listed, and listing records no view. The notification of `notification_inbox_events` is written by the inbox consumer from the outbox event, seconds later ([Internal notifications](#internal-notifications)); the invitation does not wait for it.
|
||||
- Deadline. `response_deadline_at = delivered_at + response_period_days` in whole days, set by the same UPDATE as the first delivery. The trigger of migration 00037 refuses to change the delivery, the deadline, or the period afterwards, and the mail path never touches the invitation, so neither an email nor its retries move the deadline. The mail request becomes a delivery when the delivery consumer handles it; sending notification email is planned. An unverified address, a stopped transport (`EMAIL_PROVIDER=disabled`), or a failed attempt never affects the invitation or the answer of the send.
|
||||
- Content. The email says only that an employer sent an invitation and links to `/candidate/invitations`: it names neither the organization nor the terms and holds no contact or identifier of the candidate. The notification shows the organization and the role while the candidate has not hidden the organization. The payload of `invitation.delivered` names the recipient and the organization, as the inbox contract requires, and stays on the internal event bus.
|
||||
- Visibility. A draft keeps its candidate after a C2 revocation, a hiding, or a cohort that fell below its minimum. The send derives the card handle of the stored candidate and resolves it through `candidateview.Service.ResolveCandidateHandle` again; a candidate the organization may no longer see answers 409 `state_conflict` without saying which rule applied.
|
||||
- Quota. The charge goes through the existing company quota port (`companyquota.Service.ReserveInvitation`) into `company_invitation_quota_usage`, keyed by the invitation, so it is written once. Migration 00038 adds the composite foreign key `(organization_id, invitation_id)` to `invitations`. An exhausted quota answers 429 with `Retry-After`, nothing is stored, and the draft stays. The port counts the pool of one organization; the shared E0 pool of a holding is not implemented in the port yet.
|
||||
- Idempotency. The scope is the operation, the key, the account, and the organization; the fingerprint covers the invitation of the path and `expected_version`. `invitation_send_results` keeps the outcome under the key for 24 hours together with the generic idempotency record: the original 200, a 404 of an unknown invitation, and a 409. A 400, a 412, and a 429 are not stored, so the corrected request can reuse the key. A send of an invitation that is already delivered answers 200 with its current state even with a new key or an older version and charges nothing.
|
||||
- Access. Owner only, as for drafts: `ownerCompanyOperations` at the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403.
|
||||
- Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429).
|
||||
|
||||
Not implemented: the pending limit per need and the pause after a decline or a no deal (both planned in the contract), the candidate's read of one invitation, the view and the answers, the expiry at the deadline, the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner.
|
||||
|
||||
Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (the invitation notice), `adapter/primary/http/v1/invitation_test.go` (statuses, `Retry-After`, the candidate cursor), and the integration tests `TestOrganizationInvitationSendOverHTTP` (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`.
|
||||
|
||||
## 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.
|
||||
|
||||
+1
-1
@@ -479,7 +479,7 @@ Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka):
|
||||
|
||||
Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content.
|
||||
|
||||
What these tests do not show: a real invitation (none produces an event yet), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check).
|
||||
What these tests do not show: a real invitation event through Kafka and the relay (`TestOrganizationInvitationSendOverHTTP` delivers it through the handler storage only), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check).
|
||||
|
||||
## Demo seed tests
|
||||
|
||||
|
||||
+28
-10
@@ -6,7 +6,7 @@
|
||||
|
||||
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
|
||||
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий) работает через backend API; отправка и сторона кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, отправка приглашений и ответ на них, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает уведомления; первый продуктовый источник - отправленное приглашение (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий), отправка во входящие кандидата и список приглашений кандидата работают через backend API; ответы кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений) и [Отправка приглашений](#отправка-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, ответ на приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
|
||||
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
|
||||
|
||||
@@ -412,22 +412,22 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Внутренние уведомления
|
||||
|
||||
Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Ни один продуктовый модуль пока не создает уведомления. Приглашения, первый запланированный источник, не реализованы, поэтому единственное событие, которое сегодня попадает в inbox, синтетическое, и у настоящего получателя список пуст.
|
||||
Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Отправка приглашения - первый продуктовый источник ([Отправка приглашений](#отправка-приглашений)); синтетическое событие остается для тестов и проверок.
|
||||
|
||||
Код: миграции `backend/db/migrations/00032_create_notification_inbox.sql` и `00036_allow_synthetic_notification_event.sql`, запросы `backend/db/queries/notification_inbox.sql`, модель `backend/internal/domain/notification_inbox.go`, порт `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), адаптер `adapter/secondary/postgres/notification_inbox.go`, файлы usecase `usecase/notification/inbox.go`, `inbox_handler.go` и `inbox_content.go`, HTTP-обработчик `adapter/primary/http/v1/notifications.go` с курсором `notification_cursor.go`, подключение в `bootstrap/notification.go` и `eventHandlers()` и frontend-функция `frontend/src/features/notifications/` со страницей `frontend/src/pages/notifications/`. Операции описаны в [api/README.md](../../api/README.md#уведомления).
|
||||
|
||||
- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Когда появятся приглашения, состояние "доставлено" у приглашения - это существование его строки в inbox.
|
||||
- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Состояние "доставлено" у приглашения - это его собственный `delivered_at`, который пишет транзакция отправки; строка inbox его уведомления появляется следом через обработчик.
|
||||
- Строка хранит ссылки, а не текст. В `notification_inbox_events` ключ `(recipient_user_id, event_id)` и столбцы `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at` и `read_at`. Заголовка, текста, названия, контакта и оценки там нет. Триггеры делают ссылку неизменяемой (можно только один раз задать `read_at`) и запрещают прямое удаление; удаление аккаунта получателя удаляет строки каскадом, а внешний ключ организации - `RESTRICT`. CHECK пропускает только пары типа события и типа источника из `domain.NotificationInboxSourceFor`, обе в версии схемы 1: `invitation.delivered` с `invitation` и синтетическое `notification.synthetic_delivered` с `organization`. Миграция 00032 уже развернута и не менялась; 00036 только расширила CHECK, а ее откат отказывает, пока есть синтетическая строка.
|
||||
- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Поэтому модулю приглашений не нужны изменения в таблице, обработчике и API: он добавляет `invitation.delivered` и регистрирует преобразователь содержимого для источника `invitation` в `notification.DefaultInboxSourceResolvers()`. Пока преобразователя нет, элемент такого источника показывается без содержимого.
|
||||
- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Модулю приглашений не понадобились изменения в таблице, обработчике и API: транзакция отправки добавляет `invitation.delivered` через `notification.InvitationNotifier`, а `notification.ResolveInvitationNotice` зарегистрирован для источника `invitation` в `notification.DefaultInboxSourceResolvers()`.
|
||||
- Синтетический тип события. `notification.synthetic_delivered` не имеет продуктового смысла. Он нужен, чтобы пройти весь путь (outbox, relay, Kafka, обработчик, проверка при чтении, список, прочтение) до появления настоящего источника и в браузерных тестах. По умолчанию он выключен: обработчик обрабатывает его, а inbox показывает, только при `NOTIFICATION_SYNTHETIC_ENABLED=true` (стенд разработки или браузерных тестов; overlay e2e включает его). При выключенном флаге событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого; CHECK в базе разрешает тип в любом случае, поэтому для включения миграция не нужна. Создать событие может только код, который умеет писать в outbox, а содержимое - фиксированный текст с названием отправляющей организации. Браузерный набор добавляет его через `company-fixture` (тег сборки Go `e2e`), а не через операцию пользователя.
|
||||
- Обработчик `notification_inbox`. `InboxHandler` обрабатывает разрешенные типы. В транзакции dedup-маркера он проверяет конверт и payload и окончательно отклоняет сломанное событие (`ErrEventRejected`), пропускает получателя, чей аккаунт удален, и пишет строку с `ON CONFLICT DO NOTHING` по ключу. Получатель, удаленный между проверкой и вставкой, прерывает вставку внешним ключом получателя; обработчик возвращает это как повторяемую ошибку, и повтор видит, что аккаунта нет, и пропускает событие, а ошибка внешнего ключа организации отклоняет событие окончательно. Одну строку на получателя и ID события держат три слоя: маркер обработчика, ключ и сравнение дубликата с сохраненными метаданными; ID события, который пришел снова с другими метаданными, отклоняется, а не перезаписывается. Поэтому повтор под переименованным обработчиком второй строки не создает. `occurred_at` - информационное время вставки строки outbox; вместе с ID события оно упорядочивает список. Группа `<CONSUMER_GROUP_PREFIX>.notification_inbox` новая, поэтому читает с самого раннего сохраненного события; события других типов считаются пропущенными.
|
||||
- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Единственный преобразователь сегодня - у синтетического уведомления: его фиксированный русский текст называет организацию-отправителя по ее текущему названию, которое `OrganizationNameForRecipient` читает с учетом текущего положения получателя. Кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета.
|
||||
- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Преобразователь доставленного приглашения читает его, только если оно адресовано получателю, доставлено и относится к организации элемента, и называет организацию и роль; значений кандидата он не показывает и ссылается на `/candidate/invitations`. Преобразователь синтетического уведомления использует фиксированный русский текст с названием организации-отправителя. Оба читают текущее название через `OrganizationNameForRecipient` с учетом текущего положения получателя: кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета.
|
||||
- Область доступа. Кабинет кандидата требует подтвержденный аккаунт кандидата и показывает все организации, которые писали вызывающему. Кабинет одной организации требует аккаунт работодателя с подтвержденной почтой (иначе 403 `email_not_verified`, как у других операций организации) и активное членство любой роли в организации из пути. Членство блокируется `FOR SHARE` через `LockActiveMembership` в транзакции списка или отметки, как в чтениях карточки, поэтому отзыв не может зафиксироваться между проверкой и чтением и останавливает следующий же запрос. Получатель всегда берется из сессии; организация из пути только сужает строки, а один идентификатор в пути ничего не дает. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403. Нет членства, неизвестная организация, элемент другого аккаунта, элемент другой организации и неизвестный ID дают один и тот же 404 `not_found`. Маршруты организации не входят в список только для владельца в `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` называет их проверяемыми в собственной транзакции.
|
||||
- Чтение и отметка. `GET /api/v1/me/notifications` и `GET /api/v1/organizations/{org_id}/notifications` возвращают страницу от новых к старым с курсором, привязанным к аккаунту и кабинету; курсор другого аккаунта или кабинета - 400. `POST .../{notification_id}/read` сохраняет первое время прочтения и возвращает его при каждом повторе. Он не читает источник и не возвращает содержимое, поэтому элемент без содержимого тоже можно отметить. Все четыре - `Cache-Control: no-store`; отметка требует сессию, CSRF-токен и разрешенный Origin, а Idempotency-Key не нужен, потому что операция идемпотентна по эффекту. Новых кодов problem нет.
|
||||
- Frontend. `features/notifications` экспортирует `NotificationInbox` (кандидат или одна организация) и `OrganizationNotificationInbox` (выбор организации в параметре `organization_id` и сам inbox). Их используют страницы `/candidate/notifications` и `/employer/notifications` и пункт "Уведомления" в каждой оболочке. Список читается при каждом заходе и не сохраняется (`gcTime: 0`), ключ зависит от аккаунта и кабинета, а кэш сбрасывается при смене аккаунта или сессии и при отказе в доступе. Состояния: загрузка, пусто, ошибка с повтором, нет доступа, элемент без содержимого и "Показать еще". Состояние прочтения выражено словом, а не только стилем, отметка - нативная кнопка, и после успеха фокус переходит на заголовок элемента.
|
||||
- Компромисс: согласованность в конечном счете. Строку пишет обработчик после relay и Kafka, поэтому уведомление появляется через секунды после фиксации у источника, а не внутри его транзакции. Альтернатива - писать строку в транзакции источника через `UnitOfWork.NotificationInbox()` - дала бы мгновенность, но привязала бы каждый источник к inbox и лишила бы повторов и dead-letter, которые дает обработчик. Поэтому браузерный набор ждет появления элемента и затем повторяет доставку.
|
||||
- Тесты. Модульные: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` и `inbox_handler_test.go` (проверки кабинета, отзыв членства, запасной вариант преобразователя, идемпотентный обработчик, отклоненные события, событие `invitation.delivered` по тому же контракту), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go` и тесты функции в `frontend/src/features/notifications/`. Интеграционные: `TestNotificationInboxOverHTTP` и `TestSyntheticNotificationMigration*`. Браузерный: `frontend/e2e/notifications.spec.ts` в режиме регистрации ([TESTING.md](TESTING.md#браузерный-e2e-набор)).
|
||||
- Не реализовано: источник приглашений и его преобразователь содержимого, счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет.
|
||||
- Не реализовано: счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет.
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
@@ -941,13 +941,13 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
|
||||
### Черновики приглашений
|
||||
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет. Отправка, отзыв, повышение вилки, чтение контактов и все операции кандидата тега invitation после общих проверок по-прежнему отвечают 501. Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов и все операции кандидата тега invitation, кроме `ListMyInvitations`, после общих проверок по-прежнему отвечают 501. Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
|
||||
Таблицы:
|
||||
|
||||
- `invitations`: UUIDv7 `id`, `organization_id`, внутренний `candidate_id` (его не сериализуют, не логируют и не печатают), необязательная связь с потребностью (`need_id` с `need_requirements_version`, привязанные составными внешними ключами к сохраненной версии потребности той же организации), `state` (все четырнадцать состояний контракта, поэтому последующим операциям не нужно менять ограничение), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7 или 14), `policy_version_id` (версия продуктовой политики, разрешившая срок), `response_deadline_at`, `salary_raise_used`, `created_by`, а также `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. Ограничения CHECK связывают дедлайн с доставкой (оба заданы или оба null), оставляют черновик без доставки, просмотра, ответа и повышения и связывают причину истечения с состоянием. Триггер хранит неизменными столбцы идентичности, требует, чтобы каждый UPDATE увеличивал `version` ровно на единицу, а `terms_version` не более чем на единицу, и не дает отменить повышение или сдвинуть доставку, дедлайн и срок после доставки. Второй триггер запрещает DELETE. Внешние ключи на организации, аккаунты и версии политики - `ON DELETE RESTRICT`, поэтому аккаунт с приглашениями нельзя удалить, пока процедура удаления их не закроет.
|
||||
- `invitation_terms_versions`: `(invitation_id, version)`, условия в виде снимка JSONB и вилка еще раз в типизированных столбцах (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Ограничения повторяют денежные правила в целых числах: обе границы от 1000 до 100 000 000 рублей с шагом 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B` (ширина 10-40% от середины), RUB, месяц и `net` или `gross`. Снимок обязан содержать все двенадцать условий, а его вилка - совпадать с типизированными столбцами. Триггер запрещает UPDATE и DELETE: версия условий неизменяема, изменение добавляет следующую версию. Приглашение указывает на текущую версию отложенным составным внешним ключом, поэтому первая версия вставляется в той же транзакции.
|
||||
- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created` или `draft_updated`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются.
|
||||
- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated` или, с миграции 00038, `delivered`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются.
|
||||
- `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата.
|
||||
|
||||
Решения:
|
||||
@@ -962,12 +962,30 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
- Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки.
|
||||
- Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое.
|
||||
|
||||
Как подключаются следующие операции: отправка должна снова проверить кандидата тем же барьером видимости, потому что черновик сохраняет кандидата после отзыва C2 или скрытия, и затем переводит черновик в `delivered` одним UPDATE `state`, `delivered_at`, `response_deadline_at` и `version`, добавляет событие аудита этой версии и пишет событие outbox `invitation.delivered`, а преобразователь входящей записи для источника `invitation` - уже существующая точка подключения [Внутренних уведомлений](#внутренние-уведомления); входящие кандидата читают `invitations` по `candidate_id` и `delivered_at`, а правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением.
|
||||
Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением.
|
||||
|
||||
Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, списание квоты и предел ожидающих приглашений на потребность, отправка, повышение, отзыв, сторона кандидата, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована.
|
||||
Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована.
|
||||
|
||||
Тесты: `domain/salary_range_test.go` и `domain/invitation_test.go` (точная ширина на 10% и 40%, шаг, пределы, правила условий с pointer, версии, неизменность прежних значений, скрытие при печати), `usecase/invitation/service_test.go` (политика владельца, отказы по handle, порядок проверок, повтор, откат, версии), `adapter/primary/http/v1/invitation_test.go` (преобразование, отсутствие полей кандидата, статусы отказов, курсор) и интеграционные `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` и `TestInvitationMigrationRollbackKeepsStoredInvitations` на настоящем PostgreSQL.
|
||||
|
||||
### Отправка приглашений
|
||||
|
||||
Реализовано: `SendOrganizationInvitation` и список приглашений кандидата `ListMyInvitations` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_delivery.go`, `usecase/invitation/send.go` и `candidate_inbox.go`, `usecase/notification/invitation.go`, HTTP-обработчик `adapter/primary/http/v1/invitation.go` с курсором в `invitation_cursor.go`, адаптер `adapter/secondary/postgres/invitation_delivery.go` с `db/queries/invitation_delivery.sql`, подключение в `bootstrap/invitation.go` и миграция `00038_send_invitations.sql`.
|
||||
|
||||
- Одна транзакция. Отправка берет блокировку организации (`CompanyQuotaRepository.LockOrganization`), проверку владельца по членству, Idempotency-Key и блокировку строки приглашения в порядке всех команд приглашений, а затем блокировки видимой когорты. Она снова проходит барьер видимости чтения карточки, списывает одно приглашение из квоты организации, переводит черновик в `delivered` одним условным UPDATE (`state`, `version` плюс один, `delivered_at`, `response_deadline_at`, `updated_at`; версия условий не меняется), добавляет событие аудита `delivered` и пишет события outbox: `invitation.delivered` для уведомления внутри платформы и `notification.mail_requested` со строкой `mail_requests` для письма. Внутренний шаг отправки не сохраняется: к моменту ответа приглашение уже `delivered`, лежит в списке кандидата, а списание записано. Ошибка любого шага откатывает все.
|
||||
- Входящая запись кандидата - само доставленное приглашение. `ListMyInvitations` читает строки с кандидатом из сессии и `delivered_at`, от новых к старым по `(delivered_at, id)` по частичному индексу миграции 00037, с текущим названием организации-отправителя; у черновика доставки нет, и он не показывается, а список не записывает просмотр. Уведомление в `notification_inbox_events` пишет обработчик inbox из события outbox через секунды ([Внутренние уведомления](#внутренние-уведомления)); приглашение его не ждет.
|
||||
- Срок. `response_deadline_at = delivered_at + response_period_days` в целых днях, его задает тот же UPDATE, что и первую доставку. Триггер миграции 00037 запрещает потом менять доставку, срок и период, а почтовый путь приглашения не трогает, поэтому ни письмо, ни его повторы срок не сдвигают. Запрос письма становится доставкой, когда его обрабатывает обработчик доставок; отправка писем-уведомлений запланирована. Неподтвержденный адрес, остановленный транспорт (`EMAIL_PROVIDER=disabled`) и неудачная попытка не влияют ни на приглашение, ни на ответ отправки.
|
||||
- Содержимое. Письмо сообщает только, что работодатель прислал приглашение, и ссылается на `/candidate/invitations`: в нем нет ни организации, ни условий, ни контакта или идентификатора кандидата. Уведомление показывает организацию и роль, пока кандидат не скрыл организацию. Payload `invitation.delivered` называет получателя и организацию, как требует контракт inbox, и остается во внутренней шине событий.
|
||||
- Видимость. Черновик сохраняет кандидата после отзыва C2, скрытия или падения когорты ниже минимума. Отправка выводит handle карточки сохраненного кандидата и снова разрешает его через `candidateview.Service.ResolveCandidateHandle`; кандидат, которого организация больше не вправе видеть, дает 409 `state_conflict` без указания, какое правило сработало.
|
||||
- Квота. Списание идет через существующий порт квоты компании (`companyquota.Service.ReserveInvitation`) в `company_invitation_quota_usage` с ключом по приглашению, поэтому пишется один раз. Миграция 00038 добавляет составной внешний ключ `(organization_id, invitation_id)` на `invitations`. Исчерпанная квота дает 429 с `Retry-After`, ничего не сохраняется, черновик остается. Порт считает пул одной организации; общий пул E0 холдинга в порте пока не реализован.
|
||||
- Идемпотентность. Область ключа - операция, ключ, аккаунт и организация; отпечаток покрывает приглашение из пути и `expected_version`. `invitation_send_results` хранит исход под ключом 24 часа вместе с общей записью идемпотентности: исходный 200, 404 неизвестного приглашения и 409. 400, 412 и 429 не сохраняются, поэтому исправленный запрос может использовать тот же ключ. Отправка уже доставленного приглашения отвечает 200 с текущим состоянием даже с новым ключом или старой версией и ничего не списывает.
|
||||
- Доступ. Только владелец, как для черновиков: `ownerCompanyOperations` на HTTP-границе и та же проверка в транзакции; другие роли отправлять не могут. Список кандидата требует подтвержденный аккаунт кандидата, работодатель получает 403.
|
||||
- Порядок проверок после границы: владелец, ключ (422 или повтор), приглашение (404), завершенная отправка (200), версия (412), состояние и видимость (409), затем квота (429).
|
||||
|
||||
Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), чтение одного приглашения кандидатом, просмотр и ответы, истечение по сроку, отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца.
|
||||
|
||||
Тесты: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (уведомление о приглашении), `adapter/primary/http/v1/invitation_test.go` (статусы, `Retry-After`, курсор кандидата) и интеграционные `TestOrganizationInvitationSendOverHTTP` (входящие до любого письма, повторы с одной строкой каждого вида и одним списанием, срок 3 дня при остановленной почте и повторе ее задания, видимость, устаревшая версия, только владелец, квота, страницы) и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`.
|
||||
|
||||
## Frontend
|
||||
|
||||
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
|
||||
|
||||
+1
-1
@@ -479,7 +479,7 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое.
|
||||
|
||||
Чего эти тесты не показывают: настоящее приглашение (пока ни одно не создает событие), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет).
|
||||
Чего эти тесты не показывают: событие настоящего приглашения через Kafka и relay (`TestOrganizationInvitationSendOverHTTP` доставляет его только через хранилище обработчика), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет).
|
||||
|
||||
## Тесты демонстрационного seed
|
||||
|
||||
|
||||
Reference in new issue
Block a user