feat(profile): persist candidate edits and enforce company access

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 14:15:16 +03:00
1 parent 3ab6bd91a3
commit 73c7caa225
67 files changed
+5286 -229

No files matched your search

+8 -2
View File
@@ -773,7 +773,9 @@ Known limits. A resend for an unknown or verified address skips the token and me
### Organizations and memberships
Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the organization directory are planned separately. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation.
Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the paginated directory of the current account's organizations are also implemented. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation.
The middleware in `backend/internal/adapter/primary/http/company_context.go` checks the verified employer account and active `owner` membership after session, CSRF, and parameter decoding, before the business handler or its 501 fallback. All 14 organization, need, and invitation operations are classified explicitly; a contract test requires new paths with `org_id` to be classified. Candidate-owned company hiding and C4 revocation retain their separate authorization. Request context is not cached and never replaces authorization repeated inside a business transaction. Other roles receive 403; foreign or ended memberships receive 404. `ListMyOrganizations` returns only the current employer's active memberships; a company appearing in that directory does not itself grant owner authority.
Tables:
@@ -799,7 +801,11 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni
### Candidate profile
Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test.
Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backend/internal/usecase/profile/`, the transactional `CandidateProfileRepository` port, `backend/internal/adapter/secondary/postgres/candidate.go`, and `backend/internal/adapter/primary/http/v1/profile.go`. The use case rechecks the verified candidate account inside the transaction; the owner identifier comes only from the server session. Without DATABASE_URL, the operations retain their 501 fallback. Schemas and full-replacement rules live in `api/core/components/schemas/candidate_schemas.yml` and `api/core/routes/candidate_profile.yml`. No ML service, resume file, or FSP account is required.
Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates.
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories currently remain empty until assessment-result reading is implemented and are never written by the profile form.
Tables:
+8 -2
View File
@@ -773,7 +773,9 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S
### Организации и членства
Создание, чтение и редактирование организации владельцем реализованы в `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go` и `backend/internal/bootstrap/organization.go`. Порты хранения и членства находятся в `backend/internal/port/outbound/organizations.go` и адаптере PostgreSQL. Миграция `00019_create_organization_creation_results.sql` сохраняет исходный результат создания. Общий tenant-контекст и список организаций запланированы отдельно. Поведение и проверки описаны в [документации backend](../../backend/README.md#организации).
Создание, чтение и редактирование организации владельцем реализованы в `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go` и `backend/internal/bootstrap/organization.go`. Порты хранения и членства находятся в `backend/internal/port/outbound/organizations.go` и адаптере PostgreSQL. Миграция `00019_create_organization_creation_results.sql` сохраняет исходный результат создания. Общий tenant-контекст и постраничный список своих организаций также реализованы. Поведение и проверки описаны в [документации backend](../../backend/README.md#организации).
Middleware `backend/internal/adapter/primary/http/company_context.go` проверяет подтвержденный аккаунт работодателя и активное членство `owner` после сессии, CSRF и разбора параметров, до бизнес-обработчика или ответа 501. Все 14 операций организации, потребностей и приглашений перечислены явно; контрактный тест требует классифицировать новые пути с `org_id`. Кандидатские операции скрытия компании и отзыва C4 проверяют собственные права отдельно. Контекст запроса не кешируется и не заменяет повторную проверку внутри бизнес-транзакции. Другие роли получают 403, чужое или прекращенное членство - 404. `ListMyOrganizations` возвращает только активные членства текущего работодателя; наличие компании в этом справочнике само по себе не дает полномочий владельца.
Таблицы:
@@ -799,7 +801,11 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S
### Профиль кандидата
Реализовано как хранение, домен и исходный контракт: миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом.
Собственные `GetMyProfile` и `SaveMyProfile` реализованы через `backend/internal/usecase/profile/`, транзакционный порт `CandidateProfileRepository`, адаптер `backend/internal/adapter/secondary/postgres/candidate.go` и обработчик `backend/internal/adapter/primary/http/v1/profile.go`. Usecase повторно проверяет подтвержденный кандидатский аккаунт внутри транзакции; идентификатор владельца приходит только из серверной сессии. Без DATABASE_URL остается ответ 501. Схемы и правила полного обновления находятся в `api/core/components/schemas/candidate_schemas.yml` и `api/core/routes/candidate_profile.yml`. ML, файл резюме и ФСП не нужны.
Миграция `00020_create_candidate_profile_history.sql` добавляет подтверждения пересекающихся периодов и историю версий. `experience_overlaps` перечисляет пересечения включительных календарных месяцев. Явное подтверждение связывает два индекса с точными датами в текущем запросе и его `expected_version`; прежнее подтверждение переносится только при тех же индексах и датах. Изменение работодателя или описания само по себе не меняет подтвержденные периоды. Сохраненный неподтвержденный overlap допускает только точный no-op; перед изменением профиля его надо подтвердить или исправить даты.
Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории пока возвращаются пустыми до реализации чтения результатов оценки и никогда не записываются формой профиля.
Таблицы: