feat: persist versioned organization needs

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 16:25:17 +03:00
1 parent f81cd0ae09
commit ee3738ee73
14 files changed
+2388

No files matched your search

+8
View File
@@ -40,6 +40,14 @@ The same `Idempotency-Key` and body replay the original `201` snapshot within 24
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
## Need storage
Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict. Need business endpoints remain unimplemented at this storage stage.
`requirements_version` identifies the snapshot where confirmed requirements last changed. Editing only the title, source text, or unconfirmed suggestions leaves that reference unchanged. Domain no-ops preserve both versions. Snapshots preserve provenance, reject oversized content, and use UTC microsecond timestamps. Current and historical reads require the organization ID; immutable history rejects ordinary UPDATE and DELETE. Down migration removes both tables and their history, so it is destructive after data has been written.
`TestOrganizationNeedsStorage` exercises actual PostgreSQL isolation, history, concurrent updates, transaction rollback, immutable snapshots, and storage bounds. The caller must perform the existing active-owner check in the same business operation; storage scope alone does not grant company access.
## Candidate questionnaire
Verified candidates can read and replace their own questionnaire through `GET/PUT /api/v1/me/questionnaire`. The questionnaire has a separate version and stores self-assessment, work formats, optional experience totals, and one or two specializations. It cannot assign confirmed grades. An identical retry returns the saved record without advancing its version; a stale changed body returns 412, as specified by the API contract. Concurrent identical writes also return the same winning record.
+8
View File
@@ -40,6 +40,14 @@
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
## Хранилище потребностей
Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412. На этом этапе хранилища бизнес-операции HTTP потребностей еще не реализованы.
`requirements_version` указывает на снимок последнего изменения подтвержденных требований. Правка только названия, исходного текста или неподтвержденных предложений сохраняет эту ссылку. Доменный no-op сохраняет обе версии. Снимки сохраняют происхождение полей, отклоняют слишком большой объем данных и используют время UTC с точностью до микросекунд. Чтение текущей и исторической версии требует ID организации; обычные UPDATE и DELETE истории запрещены. Откат миграции удаляет обе таблицы вместе с историей, поэтому после записи данных он приводит к их потере.
`TestOrganizationNeedsStorage` проверяет на настоящем PostgreSQL изоляцию, историю, конкурентные обновления, откат транзакции, неизменяемость снимков и ограничения объема. Вызывающая бизнес-операция должна применять существующую проверку активного владельца; область организации в хранилище сама по себе не дает доступа к компании.
## Анкета кандидата
Подтвержденный кандидат читает и заменяет собственную анкету через `GET/PUT /api/v1/me/questionnaire`. Анкета имеет отдельную версию и хранит самооценку, форматы работы, необязательные суммы опыта и одну или две специализации. Она не назначает подтвержденные грейды. Идентичный повтор возвращает сохраненную запись без повышения версии; измененное тело с устаревшей версией получает 412 согласно контракту API. Одновременные одинаковые записи также возвращают одну победившую запись.
@@ -0,0 +1,98 @@
-- +goose Up
-- Organization needs keep a current version pointer and one bounded,
-- immutable JSON snapshot for every committed version. Readiness and
-- recommendations are derived from requirements and are not frozen here.
CREATE TABLE organization_needs (
id uuid NOT NULL,
organization_id uuid NOT NULL,
current_version bigint NOT NULL,
requirements_version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT organization_needs_pkey PRIMARY KEY (id),
CONSTRAINT organization_needs_organization_id_id_key UNIQUE (organization_id, id),
CONSTRAINT organization_needs_organization_fkey FOREIGN KEY (organization_id)
REFERENCES organizations (id) ON DELETE RESTRICT,
CONSTRAINT organization_needs_current_version_positive CHECK (current_version > 0),
CONSTRAINT organization_needs_requirements_version CHECK (
requirements_version > 0 AND requirements_version <= current_version
),
CONSTRAINT organization_needs_timestamps CHECK (updated_at >= created_at)
);
-- Every version is tied to its organization-scoped need identity. The full
-- public requirement data and provenance fit under the 256 KiB snapshot cap;
-- the source text itself is bounded by the contract at 10,000 characters.
CREATE TABLE organization_need_versions (
organization_id uuid NOT NULL,
need_id uuid NOT NULL,
version bigint NOT NULL,
snapshot jsonb NOT NULL,
CONSTRAINT organization_need_versions_pkey PRIMARY KEY (organization_id, need_id, version),
CONSTRAINT organization_need_versions_need_fkey FOREIGN KEY (organization_id, need_id)
REFERENCES organization_needs (organization_id, id) ON DELETE RESTRICT,
CONSTRAINT organization_need_versions_version_positive CHECK (version > 0),
CONSTRAINT organization_need_versions_snapshot_shape CHECK (
jsonb_typeof(snapshot) = 'object'
AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version']
AND jsonb_typeof(snapshot -> 'id') = 'string'
AND snapshot ->> 'id' = need_id::text
AND jsonb_typeof(snapshot -> 'organization_id') = 'string'
AND snapshot ->> 'organization_id' = organization_id::text
AND jsonb_typeof(snapshot -> 'version') = 'number'
AND snapshot ->> 'version' = version::text
AND jsonb_typeof(snapshot -> 'requirements_version') = 'number'
AND CASE
WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$'
THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version
ELSE FALSE
END
AND octet_length(snapshot::text) <= 262144
)
);
-- The current and requirements versions must both name snapshots belonging
-- to this same organization and need. Deferral lets creation insert the
-- parent and version 1 in one transaction.
ALTER TABLE organization_needs
ADD CONSTRAINT organization_needs_current_snapshot_fkey
FOREIGN KEY (organization_id, id, current_version)
REFERENCES organization_need_versions (organization_id, need_id, version)
DEFERRABLE INITIALLY DEFERRED,
ADD CONSTRAINT organization_needs_requirements_snapshot_fkey
FOREIGN KEY (organization_id, id, requirements_version)
REFERENCES organization_need_versions (organization_id, need_id, version)
DEFERRABLE INITIALLY DEFERRED;
-- Application writes append versions only. Old snapshots remain available
-- for future history reads and cannot be edited or deleted by ordinary SQL.
-- TRUNCATE remains available to reset isolated integration databases.
-- +goose StatementBegin
CREATE FUNCTION reject_organization_need_version_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'organization_need_versions_immutable',
TABLE = 'organization_need_versions',
MESSAGE = 'need versions are immutable: append a new version instead';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER organization_need_versions_immutable
BEFORE UPDATE OR DELETE ON organization_need_versions
FOR EACH ROW EXECUTE FUNCTION reject_organization_need_version_change();
CREATE INDEX organization_needs_org_created_idx
ON organization_needs (organization_id, created_at DESC, id DESC);
-- +goose Down
DROP INDEX organization_needs_org_created_idx;
DROP TRIGGER organization_need_versions_immutable ON organization_need_versions;
DROP FUNCTION reject_organization_need_version_change();
ALTER TABLE organization_needs
DROP CONSTRAINT organization_needs_requirements_snapshot_fkey,
DROP CONSTRAINT organization_needs_current_snapshot_fkey;
DROP TABLE organization_need_versions;
DROP TABLE organization_needs;
+102
View File
@@ -0,0 +1,102 @@
-- The parent and first immutable snapshot are inserted in one caller-owned
-- transaction. Deferred version references are checked when it commits.
-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
organization_id,
current_version,
requirements_version,
created_at,
updated_at
) VALUES (
sqlc.arg(id),
sqlc.arg(organization_id),
sqlc.arg(current_version),
sqlc.arg(requirements_version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
);
-- name: InsertOrganizationNeedVersion :exec
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
) VALUES (
sqlc.arg(organization_id),
sqlc.arg(need_id),
sqlc.arg(version),
sqlc.arg(snapshot)::jsonb
);
-- Read one current version with its organization-scoped parent metadata.
-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
need.id AS need_id,
need.current_version,
need.requirements_version,
need.created_at,
need.updated_at,
version.snapshot::text AS snapshot
FROM organization_needs AS need
INNER JOIN organization_need_versions AS version
ON version.organization_id = need.organization_id
AND version.need_id = need.id
AND version.version = need.current_version
WHERE
need.organization_id = sqlc.arg(organization_id)
AND need.id = sqlc.arg(need_id);
-- Read one historical version without exposing another organization's record.
-- name: ReadOrganizationNeedVersion :one
SELECT snapshot::text AS snapshot
FROM organization_need_versions
WHERE
organization_id = sqlc.arg(organization_id)
AND need_id = sqlc.arg(need_id)
AND version = sqlc.arg(version);
-- The conditional parent update is the compare-and-swap. Appending the
-- snapshot is part of the same SQL statement, so a failed insert leaves the
-- parent pointer unchanged even before the surrounding transaction rolls
-- back. No row is returned when the expected version lost a race.
-- name: AdvanceOrganizationNeed :one
WITH advanced AS (
UPDATE organization_needs
SET
current_version = organization_needs.current_version + 1,
requirements_version = sqlc.arg(requirements_version),
updated_at = sqlc.arg(updated_at)
WHERE
organization_needs.organization_id = sqlc.arg(organization_id)
AND organization_needs.id = sqlc.arg(need_id)
AND organization_needs.current_version = sqlc.arg(expected_version)
AND sqlc.arg(next_version)::bigint = organization_needs.current_version + 1
AND (
sqlc.arg(requirements_version)::bigint = organization_needs.requirements_version
OR sqlc.arg(requirements_version)::bigint = organization_needs.current_version + 1
)
RETURNING organization_needs.organization_id, organization_needs.id, organization_needs.current_version
), appended AS (
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
)
SELECT
advanced.organization_id,
advanced.id,
advanced.current_version,
sqlc.arg(snapshot)::jsonb
FROM advanced
RETURNING
organization_need_versions.organization_id,
organization_need_versions.need_id,
organization_need_versions.version,
organization_need_versions.snapshot::text AS snapshot
)
SELECT appended.snapshot
FROM appended;
+384
View File
@@ -0,0 +1,384 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestOrganizationNeedsStorage(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := organizationFixture{
ctx: ctx,
pool: pool,
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
transactor: postgresadapter.NewTransactor(pool),
now: now,
}
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("creates current and immutable historical snapshots within organization scope", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Поиск"), now)
otherOrganization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другая компания"), now.Add(time.Minute))
created := newIntegrationNeed(t, organization.ID(), "Разработчик", now.Add(2*time.Minute))
fixture.createNeed(t, created)
initial, err := fixture.getNeed(organization.ID(), created.ID())
if err != nil || initial.Version() != 1 || initial.RequirementsVersion() != 1 ||
initial.Readiness().Status != domain.NeedReadinessIncomplete {
t.Fatalf("Get(initial need) = version %d requirements %d error %v, want incomplete version 1", initial.Version(), initial.RequirementsVersion(), err)
}
proposal := initial.Snapshot()
proposal.Title = "Backend developer"
proposal.UpdatedAt = now.Add(3 * time.Minute)
titleOnly, changed, err := initial.Revise(1, proposal)
if err != nil || !changed {
t.Fatalf("Revise(title) = changed %v error %v, want a saved change", changed, err)
}
fixture.saveNeed(t, organization.ID(), created.ID(), 1, titleOnly)
proposal = titleOnly.Snapshot()
proposal.Requirements.Specialization = domain.NeedValue[domain.SpecializationCode]{
Status: domain.NeedValueConfirmed,
Value: needIntegrationPointer(domain.SpecializationBackend),
Source: &domain.NeedValueSource{Origin: domain.NeedValueManual},
}
proposal.UpdatedAt = now.Add(4 * time.Minute)
confirmed, changed, err := titleOnly.Revise(2, proposal)
if err != nil || !changed || confirmed.RequirementsVersion() != 3 {
t.Fatalf("Revise(confirmed specialization) = requirements %d changed %v error %v, want requirements version 3", confirmed.RequirementsVersion(), changed, err)
}
fixture.saveNeed(t, organization.ID(), created.ID(), 2, confirmed)
current, err := fixture.getNeed(organization.ID(), created.ID())
if err != nil || current.Version() != 3 || current.RequirementsVersion() != 3 || current.Snapshot().Title != "Backend developer" {
t.Fatalf("Get(current need) = version %d requirements %d title %q error %v", current.Version(), current.RequirementsVersion(), current.Snapshot().Title, err)
}
first, err := fixture.getNeedVersion(organization.ID(), created.ID(), 1)
if err != nil || first.Snapshot().Title != "Разработчик" || first.RequirementsVersion() != 1 {
t.Fatalf("GetVersion(1) = title %q requirements %d error %v", first.Snapshot().Title, first.RequirementsVersion(), err)
}
second, err := fixture.getNeedVersion(organization.ID(), created.ID(), 2)
if err != nil || second.Snapshot().Title != "Backend developer" || second.RequirementsVersion() != 1 {
t.Fatalf("GetVersion(2) = title %q requirements %d error %v", second.Snapshot().Title, second.RequirementsVersion(), err)
}
if _, err := fixture.getNeed(otherOrganization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) {
t.Fatalf("Get from another organization error = %v, want ErrNeedNotFound", err)
}
if _, err := fixture.getNeedVersion(otherOrganization.ID(), created.ID(), 1); !errors.Is(err, outbound.ErrNeedNotFound) {
t.Fatalf("GetVersion from another organization error = %v, want ErrNeedNotFound", err)
}
if _, err := fixture.getNeedVersion(organization.ID(), created.ID(), 4); !errors.Is(err, outbound.ErrNeedNotFound) {
t.Fatalf("GetVersion(missing version) error = %v, want ErrNeedNotFound", err)
}
if err := fixture.createNeedError(created); !errors.Is(err, outbound.ErrNeedAlreadyExists) {
t.Fatalf("Create(duplicate ID) error = %v, want ErrNeedAlreadyExists", err)
}
})
t.Run("rejects nil scope and noninitial creation snapshots", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Первая версия"), now)
created := newIntegrationNeed(t, organization.ID(), "Черновик", now.Add(time.Minute))
for _, scope := range []struct {
name string
organizationID uuid.UUID
needID uuid.UUID
}{
{name: "organization", organizationID: uuid.Nil, needID: created.ID()},
{name: "need", organizationID: organization.ID(), needID: uuid.Nil},
} {
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := integrationNeedRepositoryForTest(unit).Get(ctx, scope.organizationID, scope.needID)
return err
})
if !errors.Is(err, domain.ErrInvalidNeed) {
t.Errorf("Get with nil %s ID error = %v, want ErrInvalidNeed", scope.name, err)
}
}
if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return integrationNeedRepositoryForTest(unit).Create(ctx, domain.Need{})
}); !errors.Is(err, domain.ErrInvalidNeed) {
t.Fatalf("Create(zero need) error = %v, want ErrInvalidNeed", err)
}
laterSnapshot := created.Snapshot()
laterSnapshot.Version = 2
later, err := domain.RestoreNeed(laterSnapshot)
if err != nil {
t.Fatalf("RestoreNeed(version 2) error = %v", err)
}
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return integrationNeedRepositoryForTest(unit).Create(ctx, later)
})
if !errors.Is(err, domain.ErrInvalidNeed) {
t.Fatalf("Create(version 2) error = %v, want ErrInvalidNeed", err)
}
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0)
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0)
})
t.Run("competing compare-and-swap updates have one winner", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Конкурент"), now)
created := newIntegrationNeed(t, organization.ID(), "Исходное название", now.Add(time.Minute))
fixture.createNeed(t, created)
concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 3))
ready := make(chan error, 2)
start := make(chan struct{})
errs := make([]error, 2)
var group sync.WaitGroup
for index := range 2 {
group.Go(func() {
errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
repository := integrationNeedRepositoryForTest(unit)
current, err := repository.Get(ctx, organization.ID(), created.ID())
if err != nil {
ready <- err
return err
}
proposal := current.Snapshot()
proposal.Title = fmt.Sprintf("Вариант %d", index+1)
proposal.UpdatedAt = now.Add(time.Duration(index+2) * time.Minute)
next, changed, err := current.Revise(1, proposal)
if err != nil {
ready <- err
return fmt.Errorf("prepare concurrent need: %w", err)
}
if !changed {
err := domain.ErrInvalidNeed
ready <- err
return fmt.Errorf("prepare concurrent need: %w", err)
}
ready <- nil
<-start
return repository.Save(ctx, organization.ID(), created.ID(), 1, next)
})
})
}
setupErrors := []error{<-ready, <-ready}
close(start)
group.Wait()
for _, err := range setupErrors {
if err != nil {
t.Fatalf("prepare concurrent need: %v", err)
}
}
successes := 0
conflicts := 0
for index, err := range errs {
switch {
case err == nil:
successes++
case errors.Is(err, outbound.ErrNeedVersionConflict):
conflicts++
default:
t.Fatalf("concurrent update %d error = %v, want success or ErrNeedVersionConflict", index, err)
}
}
if successes != 1 || conflicts != 1 {
t.Fatalf("concurrent updates had %d successes and %d conflicts, want one each", successes, conflicts)
}
current, err := fixture.getNeed(organization.ID(), created.ID())
if err != nil || current.Version() != 2 {
t.Fatalf("Get after concurrent updates = version %d, error %v, want version 2", current.Version(), err)
}
})
t.Run("create and save participate in caller rollback", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Откат"), now)
created := newIntegrationNeed(t, organization.ID(), "Новый профиль", now.Add(time.Minute))
rollback := errors.New("roll back need write")
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := integrationNeedRepositoryForTest(unit).Create(ctx, created); err != nil {
return err
}
return rollback
})
if !errors.Is(err, rollback) {
t.Fatalf("create transaction error = %v, want rollback sentinel", err)
}
if _, err := fixture.getNeed(organization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) {
t.Fatalf("Get rolled-back need error = %v, want ErrNeedNotFound", err)
}
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0)
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0)
fixture.createNeed(t, created)
current, err := fixture.getNeed(organization.ID(), created.ID())
if err != nil {
t.Fatalf("Get need before save rollback: %v", err)
}
proposal := current.Snapshot()
proposal.Title = "Не сохранять"
proposal.UpdatedAt = now.Add(2 * time.Minute)
next, changed, err := current.Revise(1, proposal)
if err != nil || !changed {
t.Fatalf("Revise before rollback = changed %t, error %v", changed, err)
}
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := integrationNeedRepositoryForTest(unit).Save(ctx, organization.ID(), created.ID(), 1, next); err != nil {
return err
}
return rollback
})
if !errors.Is(err, rollback) {
t.Fatalf("save transaction error = %v, want rollback sentinel", err)
}
current, err = fixture.getNeed(organization.ID(), created.ID())
if err != nil || current.Version() != 1 || current.Snapshot().Title != "Новый профиль" {
t.Fatalf("Get after rolled-back save = version %d title %q error %v", current.Version(), current.Snapshot().Title, err)
}
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1)
})
t.Run("database bounds snapshots and rejects update or deletion", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Версии"), now)
created := newIntegrationNeed(t, organization.ID(), "Неизменяемая версия", now.Add(time.Minute))
fixture.createNeed(t, created)
_, err := pool.Exec(ctx, `UPDATE organization_need_versions SET snapshot = snapshot WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID())
assertSQLError(t, "update immutable need snapshot", err, "23000", "organization_need_versions_immutable")
_, err = pool.Exec(ctx, `DELETE FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID())
assertSQLError(t, "delete immutable need snapshot", err, "23000", "organization_need_versions_immutable")
assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1)
padded := created.Snapshot()
encoded, err := json.Marshal(padded)
if err != nil {
t.Fatalf("marshal snapshot for storage-bound check: %v", err)
}
var body map[string]any
if err := json.Unmarshal(encoded, &body); err != nil {
t.Fatalf("decode snapshot for storage-bound check: %v", err)
}
insertRejectedSnapshot := func(id uuid.UUID, snapshot []byte, name string) {
t.Helper()
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin %s transaction: %v", name, err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
if _, err := tx.Exec(ctx, `INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at) VALUES ($1, $2, 1, 1, $3, $3)`, id, organization.ID(), now); err != nil {
t.Fatalf("insert parent for %s: %v", name, err)
}
_, err = tx.Exec(ctx, `INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot) VALUES ($1, $2, 1, $3::jsonb)`, organization.ID(), id, snapshot)
assertSQLError(t, name, err, organizationCheckViolation, "organization_need_versions_snapshot_shape")
}
invalidTypeID := uuid.New()
body["id"] = invalidTypeID.String()
body["requirements_version"] = "1"
invalidRequirementsVersion, err := json.Marshal(body)
if err != nil {
t.Fatalf("encode snapshot with invalid requirements version type: %v", err)
}
insertRejectedSnapshot(invalidTypeID, invalidRequirementsVersion, "insert string requirements version")
largeID := uuid.New()
body["id"] = largeID.String()
body["requirements_version"] = 1
body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotBytes+1)
oversized, err := json.Marshal(body)
if err != nil {
t.Fatalf("encode oversized storage snapshot: %v", err)
}
insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot")
})
}
func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) {
t.Helper()
if err := fixture.createNeedError(need); err != nil {
t.Fatalf("Create(need) error = %v", err)
}
}
func (fixture organizationFixture) createNeedError(need domain.Need) error {
return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return integrationNeedRepositoryForTest(unit).Create(ctx, need)
})
}
func (fixture organizationFixture) getNeed(organizationID, needID uuid.UUID) (domain.Need, error) {
var need domain.Need
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
need, err = integrationNeedRepositoryForTest(unit).Get(ctx, organizationID, needID)
return err
})
return need, err
}
func (fixture organizationFixture) getNeedVersion(organizationID, needID uuid.UUID, version int64) (domain.Need, error) {
var need domain.Need
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
need, err = integrationNeedRepositoryForTest(unit).GetVersion(ctx, organizationID, needID, version)
return err
})
return need, err
}
func (fixture organizationFixture) saveNeed(t *testing.T, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) {
t.Helper()
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return integrationNeedRepositoryForTest(unit).Save(ctx, organizationID, needID, expectedVersion, next)
}); err != nil {
t.Fatalf("Save(need) error = %v", err)
}
}
func integrationNeedRepositoryForTest(unit outbound.UnitOfWork) outbound.NeedRepository {
repositories, ok := unit.(outbound.NeedRepositories)
if !ok {
panic("unit of work does not expose need repositories")
}
return repositories.Needs()
}
func newIntegrationNeed(t *testing.T, organizationID uuid.UUID, title string, at time.Time) domain.Need {
t.Helper()
need, err := domain.NewNeed(domain.NeedSnapshot{
ID: uuid.New(), OrganizationID: organizationID, Title: title, Version: 1, RequirementsVersion: 1,
Requirements: domain.EmptyNeedRequirements(), CreatedAt: at, UpdatedAt: at,
})
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
return need
}
func needIntegrationPointer[T any](value T) *T { return &value }
@@ -39,6 +39,7 @@ var (
// organizationTables are emptied together: memberships reference both
// users and organizations. Creation snapshots reference idempotency records.
organizationTables = []pgx.Identifier{
{"organization_need_versions"}, {"organization_needs"},
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
}
@@ -0,0 +1,276 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.NeedRepository = needRepository{}
func (unit *UnitOfWork) Needs() outbound.NeedRepository {
return needRepository{queries: unit.queries}
}
type needRepository struct {
queries *sqlc.Queries
}
func (repository needRepository) Create(ctx context.Context, need domain.Need) error {
const location = "needRepository.Create"
snapshot, encoded, err := encodeNeedSnapshot(need)
if err != nil {
return fmt.Errorf("%s - validate and encode need: %w", location, err)
}
if snapshot.Version != 1 || snapshot.RequirementsVersion != 1 {
return fmt.Errorf("%s - creation must start at version 1: %w", location, domain.ErrInvalidNeed)
}
if err := repository.queries.InsertOrganizationNeed(ctx, sqlc.InsertOrganizationNeedParams{
ID: pgUUID(snapshot.ID),
OrganizationID: pgUUID(snapshot.OrganizationID),
CurrentVersion: snapshot.Version,
RequirementsVersion: snapshot.RequirementsVersion,
CreatedAt: pgTime(snapshot.CreatedAt),
UpdatedAt: pgTime(snapshot.UpdatedAt),
}); err != nil {
return fmt.Errorf("%s - insert need: %w", location, mapNeedError(err))
}
if err := repository.queries.InsertOrganizationNeedVersion(ctx, sqlc.InsertOrganizationNeedVersionParams{
OrganizationID: pgUUID(snapshot.OrganizationID),
NeedID: pgUUID(snapshot.ID),
Version: snapshot.Version,
Snapshot: encoded,
}); err != nil {
return fmt.Errorf("%s - append initial need snapshot: %w", location, mapNeedError(err))
}
return nil
}
func (repository needRepository) Get(ctx context.Context, organizationID, needID uuid.UUID) (domain.Need, error) {
const location = "needRepository.Get"
if err := validateNeedScope(location, organizationID, needID); err != nil {
return domain.Need{}, err
}
row, err := repository.queries.ReadCurrentOrganizationNeed(ctx, sqlc.ReadCurrentOrganizationNeedParams{
OrganizationID: pgUUID(organizationID),
NeedID: pgUUID(needID),
})
if err != nil {
return domain.Need{}, fmt.Errorf("%s - read current need: %w", location, mapNeedNoRows(err))
}
if !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
return domain.Need{}, fmt.Errorf("%s - stored need timestamps are invalid", location)
}
return restoreNeedSnapshot(location, row.Snapshot, organizationID, needID, row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time)
}
func (repository needRepository) GetVersion(
ctx context.Context,
organizationID, needID uuid.UUID,
version int64,
) (domain.Need, error) {
const location = "needRepository.GetVersion"
if err := validateNeedScope(location, organizationID, needID); err != nil {
return domain.Need{}, err
}
if version < 1 {
return domain.Need{}, fmt.Errorf("%s - version must be positive: %w", location, domain.ErrInvalidNeed)
}
encoded, err := repository.queries.ReadOrganizationNeedVersion(ctx, sqlc.ReadOrganizationNeedVersionParams{
OrganizationID: pgUUID(organizationID),
NeedID: pgUUID(needID),
Version: version,
})
if err != nil {
return domain.Need{}, fmt.Errorf("%s - read historical need: %w", location, mapNeedNoRows(err))
}
return restoreNeedSnapshot(location, encoded, organizationID, needID, version, 0, nil, nil)
}
func (repository needRepository) Save(
ctx context.Context,
organizationID, needID uuid.UUID,
expectedVersion int64,
next domain.Need,
) error {
const location = "needRepository.Save"
if err := validateNeedScope(location, organizationID, needID); err != nil {
return err
}
if expectedVersion < 1 || next.IsZero() || next.ID() != needID || next.OrganizationID() != organizationID {
return fmt.Errorf("%s - need and expected version are invalid: %w", location, domain.ErrInvalidNeed)
}
current, err := repository.getCurrent(ctx, location, organizationID, needID)
if err != nil {
return err
}
if current.Version() != expectedVersion {
return fmt.Errorf("%s - expected version is stale: %w", location, outbound.ErrNeedVersionConflict)
}
if !current.IsNextVersionOf(next, expectedVersion) {
return fmt.Errorf("%s - next snapshot does not follow the current need: %w", location, domain.ErrInvalidNeed)
}
snapshot, encoded, err := encodeNeedSnapshot(next)
if err != nil {
return fmt.Errorf("%s - validate and encode next snapshot: %w", location, err)
}
stored, err := repository.queries.AdvanceOrganizationNeed(ctx, sqlc.AdvanceOrganizationNeedParams{
RequirementsVersion: snapshot.RequirementsVersion,
UpdatedAt: pgTime(snapshot.UpdatedAt),
OrganizationID: pgUUID(organizationID),
NeedID: pgUUID(needID),
ExpectedVersion: expectedVersion,
NextVersion: snapshot.Version,
Snapshot: encoded,
})
if errors.Is(err, pgx.ErrNoRows) {
return repository.classifyAdvanceMiss(ctx, location, organizationID, needID, expectedVersion)
}
if err != nil {
return fmt.Errorf("%s - append next snapshot and advance current version: %w", location, mapNeedError(err))
}
if _, err := restoreNeedSnapshot(location, stored, organizationID, needID, snapshot.Version, snapshot.RequirementsVersion, &snapshot.CreatedAt, &snapshot.UpdatedAt); err != nil {
return fmt.Errorf("%s - verify appended snapshot: %w", location, err)
}
return nil
}
func (repository needRepository) getCurrent(
ctx context.Context,
location string,
organizationID, needID uuid.UUID,
) (domain.Need, error) {
row, err := repository.queries.ReadCurrentOrganizationNeed(ctx, sqlc.ReadCurrentOrganizationNeedParams{
OrganizationID: pgUUID(organizationID),
NeedID: pgUUID(needID),
})
if err != nil {
return domain.Need{}, fmt.Errorf("%s - read current need: %w", location, mapNeedNoRows(err))
}
if !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
return domain.Need{}, fmt.Errorf("%s - stored need timestamps are invalid", location)
}
return restoreNeedSnapshot(location, row.Snapshot, organizationID, needID, row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time)
}
func (repository needRepository) classifyAdvanceMiss(
ctx context.Context,
location string,
organizationID, needID uuid.UUID,
expectedVersion int64,
) error {
current, err := repository.getCurrent(ctx, location, organizationID, needID)
if errors.Is(err, outbound.ErrNeedNotFound) {
return err
}
if err != nil {
return fmt.Errorf("%s - classify compare-and-swap miss: %w", location, err)
}
if current.Version() != expectedVersion {
return fmt.Errorf("%s - another writer advanced the need: %w", location, outbound.ErrNeedVersionConflict)
}
return fmt.Errorf("%s - compare-and-swap missed without a version change: %w", location, outbound.ErrTransactionConflict)
}
func encodeNeedSnapshot(need domain.Need) (domain.NeedSnapshot, []byte, error) {
if need.IsZero() {
return domain.NeedSnapshot{}, nil, domain.ErrInvalidNeed
}
snapshot := need.Snapshot()
// PostgreSQL stores timestamptz with microsecond precision. Canonicalize
// the immutable payload to the same precision as the parent row.
snapshot.CreatedAt = snapshot.CreatedAt.UTC().Truncate(time.Microsecond)
snapshot.UpdatedAt = snapshot.UpdatedAt.UTC().Truncate(time.Microsecond)
validated, err := domain.RestoreNeed(snapshot)
if err != nil {
return domain.NeedSnapshot{}, nil, err
}
snapshot = validated.Snapshot()
encoded, err := json.Marshal(snapshot)
if err != nil {
return domain.NeedSnapshot{}, nil, fmt.Errorf("encode need snapshot: %w", err)
}
if len(encoded) > domain.MaxNeedSnapshotBytes {
return domain.NeedSnapshot{}, nil, fmt.Errorf("need snapshot exceeds its storage bound: %w", domain.ErrInvalidNeed)
}
return snapshot, encoded, nil
}
func restoreNeedSnapshot(
location string,
encoded string,
organizationID, needID uuid.UUID,
version, requirementsVersion int64,
createdAt, updatedAt *time.Time,
) (domain.Need, error) {
if len(encoded) > domain.MaxNeedSnapshotBytes {
return domain.Need{}, fmt.Errorf("%s - stored snapshot exceeds its bound", location)
}
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
decoder.DisallowUnknownFields()
var snapshot domain.NeedSnapshot
if err := decoder.Decode(&snapshot); err != nil {
return domain.Need{}, fmt.Errorf("%s - stored snapshot is invalid", location)
}
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
return domain.Need{}, fmt.Errorf("%s - stored snapshot has trailing data", location)
}
if snapshot.ID != needID || snapshot.OrganizationID != organizationID || snapshot.Version != version {
return domain.Need{}, fmt.Errorf("%s - stored snapshot identity or version does not match its scope", location)
}
if requirementsVersion > 0 && snapshot.RequirementsVersion != requirementsVersion {
return domain.Need{}, fmt.Errorf("%s - stored requirements version does not match its parent", location)
}
if createdAt != nil && !snapshot.CreatedAt.UTC().Truncate(time.Microsecond).Equal(createdAt.UTC().Truncate(time.Microsecond)) {
return domain.Need{}, fmt.Errorf("%s - stored creation time does not match its parent", location)
}
if updatedAt != nil && !snapshot.UpdatedAt.UTC().Truncate(time.Microsecond).Equal(updatedAt.UTC().Truncate(time.Microsecond)) {
return domain.Need{}, fmt.Errorf("%s - stored update time does not match its parent", location)
}
need, err := domain.RestoreNeed(snapshot)
if err != nil {
return domain.Need{}, fmt.Errorf("%s - restore domain snapshot: %w", location, err)
}
return need, nil
}
func validateNeedScope(location string, organizationID, needID uuid.UUID) error {
if organizationID == uuid.Nil || needID == uuid.Nil {
return fmt.Errorf("%s - organization and need IDs must be set: %w", location, domain.ErrInvalidNeed)
}
return nil
}
func mapNeedNoRows(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ErrNeedNotFound
}
return mapNeedError(err)
}
func mapNeedError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_needs_organization_fkey" {
return fmt.Errorf("postgres.mapNeedError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
}
if pgError.Code == uniqueViolationCode && pgError.ConstraintName == "organization_needs_pkey" {
return fmt.Errorf("postgres.mapNeedError - need ID already exists: %w", outbound.ErrNeedAlreadyExists)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
@@ -396,6 +396,22 @@ type OrganizationCreationResult struct {
Snapshot []byte
}
type OrganizationNeed struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type OrganizationNeedVersion struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
Snapshot []byte
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
@@ -0,0 +1,226 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: needs.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceOrganizationNeed = `-- name: AdvanceOrganizationNeed :one
WITH advanced AS (
UPDATE organization_needs
SET
current_version = organization_needs.current_version + 1,
requirements_version = $1,
updated_at = $2
WHERE
organization_needs.organization_id = $3
AND organization_needs.id = $4
AND organization_needs.current_version = $5
AND $6::bigint = organization_needs.current_version + 1
AND (
$1::bigint = organization_needs.requirements_version
OR $1::bigint = organization_needs.current_version + 1
)
RETURNING organization_needs.organization_id, organization_needs.id, organization_needs.current_version
), appended AS (
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
)
SELECT
advanced.organization_id,
advanced.id,
advanced.current_version,
$7::jsonb
FROM advanced
RETURNING
organization_need_versions.organization_id,
organization_need_versions.need_id,
organization_need_versions.version,
organization_need_versions.snapshot::text AS snapshot
)
SELECT appended.snapshot
FROM appended
`
type AdvanceOrganizationNeedParams struct {
RequirementsVersion int64
UpdatedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
NeedID pgtype.UUID
ExpectedVersion int64
NextVersion int64
Snapshot []byte
}
// The conditional parent update is the compare-and-swap. Appending the
// snapshot is part of the same SQL statement, so a failed insert leaves the
// parent pointer unchanged even before the surrounding transaction rolls
// back. No row is returned when the expected version lost a race.
func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrganizationNeedParams) (string, error) {
row := q.db.QueryRow(ctx, advanceOrganizationNeed,
arg.RequirementsVersion,
arg.UpdatedAt,
arg.OrganizationID,
arg.NeedID,
arg.ExpectedVersion,
arg.NextVersion,
arg.Snapshot,
)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
organization_id,
current_version,
requirements_version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
`
type InsertOrganizationNeedParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The parent and first immutable snapshot are inserted in one caller-owned
// transaction. Deferred version references are checked when it commits.
func (q *Queries) InsertOrganizationNeed(ctx context.Context, arg InsertOrganizationNeedParams) error {
_, err := q.db.Exec(ctx, insertOrganizationNeed,
arg.ID,
arg.OrganizationID,
arg.CurrentVersion,
arg.RequirementsVersion,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganizationNeedVersion = `-- name: InsertOrganizationNeedVersion :exec
INSERT INTO organization_need_versions (
organization_id,
need_id,
version,
snapshot
) VALUES (
$1,
$2,
$3,
$4::jsonb
)
`
type InsertOrganizationNeedVersionParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
Snapshot []byte
}
func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertOrganizationNeedVersionParams) error {
_, err := q.db.Exec(ctx, insertOrganizationNeedVersion,
arg.OrganizationID,
arg.NeedID,
arg.Version,
arg.Snapshot,
)
return err
}
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
need.id AS need_id,
need.current_version,
need.requirements_version,
need.created_at,
need.updated_at,
version.snapshot::text AS snapshot
FROM organization_needs AS need
INNER JOIN organization_need_versions AS version
ON version.organization_id = need.organization_id
AND version.need_id = need.id
AND version.version = need.current_version
WHERE
need.organization_id = $1
AND need.id = $2
`
type ReadCurrentOrganizationNeedParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
}
type ReadCurrentOrganizationNeedRow struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Snapshot string
}
// Read one current version with its organization-scoped parent metadata.
func (q *Queries) ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error) {
row := q.db.QueryRow(ctx, readCurrentOrganizationNeed, arg.OrganizationID, arg.NeedID)
var i ReadCurrentOrganizationNeedRow
err := row.Scan(
&i.OrganizationID,
&i.NeedID,
&i.CurrentVersion,
&i.RequirementsVersion,
&i.CreatedAt,
&i.UpdatedAt,
&i.Snapshot,
)
return i, err
}
const readOrganizationNeedVersion = `-- name: ReadOrganizationNeedVersion :one
SELECT snapshot::text AS snapshot
FROM organization_need_versions
WHERE
organization_id = $1
AND need_id = $2
AND version = $3
`
type ReadOrganizationNeedVersionParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
Version int64
}
// Read one historical version without exposing another organization's record.
func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error) {
row := q.db.QueryRow(ctx, readOrganizationNeedVersion, arg.OrganizationID, arg.NeedID, arg.Version)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
@@ -30,6 +30,11 @@ type Querier interface {
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// The conditional parent update is the compare-and-swap. Appending the
// snapshot is part of the same SQL statement, so a failed insert leaves the
// parent pointer unchanged even before the surrounding transaction rolls
// back. No row is returned when the expected version lost a race.
AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrganizationNeedParams) (string, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
@@ -353,6 +358,10 @@ type Querier interface {
// transaction at commit unless an active owner membership was inserted in
// it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// The parent and first immutable snapshot are inserted in one caller-owned
// transaction. Deferred version references are checked when it commits.
InsertOrganizationNeed(ctx context.Context, arg InsertOrganizationNeedParams) error
InsertOrganizationNeedVersion(ctx context.Context, arg InsertOrganizationNeedVersionParams) error
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
@@ -533,6 +542,10 @@ type Querier interface {
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// The organization-facing read of a candidate's publication: the effective
// view (published and backed by an unrevoked C2) and no hiding of the reading
// organization. No row means the organization reads nothing, whichever of
+835
View File
@@ -0,0 +1,835 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"reflect"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
var (
// ErrInvalidNeed reports a need value that breaks the public contract or
// cannot be restored from storage.
ErrInvalidNeed = errors.New("invalid need")
// ErrNeedVersionConflict reports that a need changed after the caller read
// it. The current HTTP contract maps this condition to 412.
ErrNeedVersionConflict = errors.New("need changed concurrently")
)
const (
maxNeedTitleRunes = 200
maxNeedSourceTextRunes = 10000
maxNeedNameRunes = 100
maxNeedTaskRunes = 300
maxNeedQuoteRunes = 300
maxNeedSkillItems = 30
maxNeedTaskItems = 20
maxNeedWorkFormats = 3
MaxNeedSnapshotBytes = 262144
redactedNeed = "[redacted need]"
)
// NeedValueStatus is the confirmation state of one need field.
type NeedValueStatus string
const (
NeedValueConfirmed NeedValueStatus = "confirmed"
NeedValueExtracted NeedValueStatus = "extracted"
NeedValueUnknown NeedValueStatus = "unknown"
)
// NeedItemStatus is the confirmation state of a skill or task item.
type NeedItemStatus string
const (
NeedItemConfirmed NeedItemStatus = "confirmed"
NeedItemExtracted NeedItemStatus = "extracted"
)
// NeedValueOrigin identifies where a need value came from.
type NeedValueOrigin string
const (
NeedValueManual NeedValueOrigin = "manual"
NeedValueExtractedFromText NeedValueOrigin = "extracted_from_text"
NeedValueImported NeedValueOrigin = "imported"
)
// NeedValueSource preserves the provenance fields returned by the need
// contract. Quotes and source text are private employer content.
type NeedValueSource struct {
Origin NeedValueOrigin `json:"origin"`
Quote *string `json:"quote"`
ExtractedInVersion *int64 `json:"extracted_in_version"`
ExtractionVersion *string `json:"extraction_version"`
}
// NeedValue is one nullable scalar or list with its confirmation state and
// provenance. Unknown values have nil Value and Source.
type NeedValue[T any] struct {
Status NeedValueStatus `json:"status"`
Value *T `json:"value"`
Source *NeedValueSource `json:"source"`
}
// NeedWorkFormat is an employer-supported work format.
type NeedWorkFormat string
const (
NeedWorkFormatRemote NeedWorkFormat = "remote"
NeedWorkFormatOffice NeedWorkFormat = "office"
NeedWorkFormatHybrid NeedWorkFormat = "hybrid"
)
func (format NeedWorkFormat) IsKnown() bool {
switch format {
case NeedWorkFormatRemote, NeedWorkFormatOffice, NeedWorkFormatHybrid:
return true
default:
return false
}
}
// NeedSalaryRange is a monthly RUB range with an explicit tax basis.
type NeedSalaryRange struct {
SalaryFrom int64 `json:"salary_from"`
SalaryTo int64 `json:"salary_to"`
Currency string `json:"currency"`
Period string `json:"period"`
TaxBasis string `json:"tax_basis"`
}
// NeedSkill is one ordered required or desired skill. TaxonomyCode is nil
// when the platform has no reviewed mapping for the supplied name.
type NeedSkill struct {
Name string `json:"name"`
TaxonomyCode *string `json:"taxonomy_code"`
Status NeedItemStatus `json:"status"`
Source NeedValueSource `json:"source"`
}
// NeedTask is one ordered description of the team's work.
type NeedTask struct {
Text string `json:"text"`
Status NeedItemStatus `json:"status"`
Source NeedValueSource `json:"source"`
}
// NeedRequirements is the complete versioned requirement set. Readiness and
// recommendations are derived from this data and are not stored in a version
// snapshot.
type NeedRequirements struct {
Specialization NeedValue[SpecializationCode] `json:"specialization"`
Grade NeedValue[GradeCode] `json:"grade"`
RequiredSkills []NeedSkill `json:"required_skills"`
DesiredSkills []NeedSkill `json:"desired_skills"`
Tasks []NeedTask `json:"tasks"`
Domain NeedValue[string] `json:"domain"`
WorkFormats NeedValue[[]NeedWorkFormat] `json:"work_formats"`
Location NeedValue[string] `json:"location"`
Salary NeedValue[NeedSalaryRange] `json:"salary"`
}
// EmptyNeedRequirements returns the contract's explicit unknown values and
// empty lists. It never supplies inferred defaults.
func EmptyNeedRequirements() NeedRequirements {
return NeedRequirements{
Specialization: NeedValue[SpecializationCode]{Status: NeedValueUnknown},
Grade: NeedValue[GradeCode]{Status: NeedValueUnknown},
RequiredSkills: []NeedSkill{},
DesiredSkills: []NeedSkill{},
Tasks: []NeedTask{},
Domain: NeedValue[string]{Status: NeedValueUnknown},
WorkFormats: NeedValue[[]NeedWorkFormat]{Status: NeedValueUnknown},
Location: NeedValue[string]{Status: NeedValueUnknown},
Salary: NeedValue[NeedSalaryRange]{Status: NeedValueUnknown},
}
}
// NeedSnapshot is the complete immutable business state of one need version.
// Derived readiness and recommendations are computed separately.
type NeedSnapshot struct {
ID uuid.UUID `json:"id"`
OrganizationID uuid.UUID `json:"organization_id"`
VacancyID *uuid.UUID `json:"vacancy_id"`
Title string `json:"title"`
SourceText *string `json:"source_text"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
Requirements NeedRequirements `json:"requirements"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// Need is one immutable version of an organization's hiring need. Snapshot
// returns a defensive copy, including nested slices and pointers.
type Need struct {
snapshot NeedSnapshot
}
// NewNeed creates the initial version of a need. Creation always starts at
// version 1 and requirements_version 1, including an incomplete need.
func NewNeed(snapshot NeedSnapshot) (Need, error) {
const location = "domain.NewNeed"
if snapshot.Version != 1 || snapshot.RequirementsVersion != 1 {
return Need{}, invalidNeed(location, "a new need must start at version 1")
}
return RestoreNeed(snapshot)
}
// RestoreNeed validates a current or historical need snapshot from storage.
func RestoreNeed(snapshot NeedSnapshot) (Need, error) {
const location = "domain.RestoreNeed"
snapshot.CreatedAt = canonicalNeedTime(snapshot.CreatedAt)
snapshot.UpdatedAt = canonicalNeedTime(snapshot.UpdatedAt)
if err := validateNeedSnapshot(location, snapshot); err != nil {
return Need{}, err
}
return Need{snapshot: cloneNeedSnapshot(snapshot)}, nil
}
func canonicalNeedTime(value time.Time) time.Time {
if value.IsZero() {
return value
}
return value.UTC().Truncate(time.Microsecond)
}
func invalidNeed(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidNeed)
}
// Snapshot returns a defensive copy suitable for persistence or mapping.
func (need Need) Snapshot() NeedSnapshot { return cloneNeedSnapshot(need.snapshot) }
func (need Need) ID() uuid.UUID { return need.snapshot.ID }
func (need Need) OrganizationID() uuid.UUID { return need.snapshot.OrganizationID }
func (need Need) Version() int64 { return need.snapshot.Version }
func (need Need) RequirementsVersion() int64 { return need.snapshot.RequirementsVersion }
func (need Need) CreatedAt() time.Time { return need.snapshot.CreatedAt }
func (need Need) UpdatedAt() time.Time { return need.snapshot.UpdatedAt }
func (need Need) IsZero() bool { return need.snapshot.ID == uuid.Nil }
// Revise applies a fully merged proposal. A no-op returns the current need
// before checking expectedVersion, matching the API's 200-before-412 order.
// A real change advances the need version once. requirements_version advances
// only when the confirmed requirement projection changes.
func (need Need) Revise(expectedVersion int64, proposal NeedSnapshot) (Need, bool, error) {
const location = "domain.Need.Revise"
if need.IsZero() {
return Need{}, false, invalidNeed(location, "current need must be restored")
}
if proposal.ID != need.snapshot.ID || proposal.OrganizationID != need.snapshot.OrganizationID ||
proposal.CreatedAt.IsZero() || !proposal.CreatedAt.Equal(need.snapshot.CreatedAt) {
return Need{}, false, invalidNeed(location, "need identity and creation time cannot change")
}
if sameNeedContent(need.snapshot, proposal) {
return need, false, nil
}
if expectedVersion != need.snapshot.Version {
return Need{}, false, ErrNeedVersionConflict
}
if need.snapshot.Version == int64(^uint64(0)>>1) {
return Need{}, false, invalidNeed(location, "version cannot advance beyond the supported range")
}
proposal.Version = need.snapshot.Version + 1
if sameConfirmedNeedRequirements(need.snapshot.Requirements, proposal.Requirements) {
proposal.RequirementsVersion = need.snapshot.RequirementsVersion
} else {
proposal.RequirementsVersion = proposal.Version
}
if proposal.UpdatedAt.Before(need.snapshot.UpdatedAt) {
return Need{}, false, invalidNeed(location, "updated time cannot move backwards")
}
next, err := RestoreNeed(proposal)
if err != nil {
return Need{}, false, err
}
return next, true, nil
}
// IsNextVersionOf checks that candidate is the single next version of need.
// The repository uses it before appending an immutable snapshot.
func (need Need) IsNextVersionOf(candidate Need, expectedVersion int64) bool {
if need.IsZero() || candidate.IsZero() || expectedVersion != need.Version() ||
need.Version() == int64(^uint64(0)>>1) ||
need.snapshot.ID != candidate.snapshot.ID || need.snapshot.OrganizationID != candidate.snapshot.OrganizationID ||
!need.snapshot.CreatedAt.Equal(candidate.snapshot.CreatedAt) || candidate.Version() != need.Version()+1 ||
candidate.UpdatedAt().Before(need.UpdatedAt()) {
return false
}
if sameConfirmedNeedRequirements(need.snapshot.Requirements, candidate.snapshot.Requirements) {
return candidate.RequirementsVersion() == need.RequirementsVersion()
}
return candidate.RequirementsVersion() == candidate.Version()
}
// NeedMissingFieldName names a critical requirement used by readiness.
type NeedMissingFieldName string
const (
NeedMissingSpecialization NeedMissingFieldName = "specialization"
NeedMissingGrade NeedMissingFieldName = "grade"
NeedMissingRequiredSkills NeedMissingFieldName = "required_skills"
NeedMissingWorkFormats NeedMissingFieldName = "work_formats"
NeedMissingLocation NeedMissingFieldName = "location"
NeedMissingSalary NeedMissingFieldName = "salary"
)
// NeedMissingReason distinguishes an absent value from an unconfirmed
// suggestion.
type NeedMissingReason string
const (
NeedMissingUnknown NeedMissingReason = "unknown"
NeedMissingUnconfirmed NeedMissingReason = "unconfirmed"
)
// NeedMissingField describes one critical field and the next question shown
// to the employer.
type NeedMissingField struct {
Field NeedMissingFieldName `json:"field"`
Reason NeedMissingReason `json:"reason"`
Question string `json:"question"`
}
// NeedReadinessStatus is the completion state derived from the current need.
type NeedReadinessStatus string
const (
NeedReadinessComplete NeedReadinessStatus = "complete"
NeedReadinessIncomplete NeedReadinessStatus = "incomplete"
)
// NeedReadinessReport lists critical fields without confirmed values.
type NeedReadinessReport struct {
Status NeedReadinessStatus `json:"status"`
MissingFields []NeedMissingField `json:"missing_fields"`
}
// Readiness computes critical missing fields in the order defined by the
// contract. Location is required only for confirmed office or hybrid work.
func (need Need) Readiness() NeedReadinessReport {
requirements := need.snapshot.Requirements
missing := make([]NeedMissingField, 0, 6)
appendValue := func(field NeedMissingFieldName, status NeedValueStatus, unknownQuestion, unconfirmedQuestion string) {
if status == NeedValueConfirmed {
return
}
reason := NeedMissingUnknown
question := unknownQuestion
if status == NeedValueExtracted {
reason = NeedMissingUnconfirmed
question = unconfirmedQuestion
}
missing = append(missing, NeedMissingField{Field: field, Reason: reason, Question: question})
}
appendValue(NeedMissingSpecialization, requirements.Specialization.Status,
"Какая специализация нужна?", "Подтвердите специализацию, найденную в описании.")
appendValue(NeedMissingGrade, requirements.Grade.Status,
"Какой грейд нужен: Intern, Junior, Middle или Senior?", "Подтвердите грейд, найденный в описании.")
if !hasConfirmedNeedSkill(requirements.RequiredSkills) {
reason := NeedMissingUnknown
question := "Какие навыки обязательны для работы?"
if len(requirements.RequiredSkills) > 0 {
reason = NeedMissingUnconfirmed
question = "Подтвердите обязательные навыки, найденные в описании."
}
missing = append(missing, NeedMissingField{Field: NeedMissingRequiredSkills, Reason: reason, Question: question})
}
appendValue(NeedMissingWorkFormats, requirements.WorkFormats.Status,
"Какой формат работы вы предлагаете?", "Подтвердите формат работы, найденный в описании.")
if confirmedNeedNeedsLocation(requirements.WorkFormats) {
appendValue(NeedMissingLocation, requirements.Location.Status,
"В каком городе находится офис или гибридное рабочее место?", "Подтвердите место работы, найденное в описании.")
}
appendValue(NeedMissingSalary, requirements.Salary.Status,
"Какую вилку в рублях вы предлагаете и в какой базе: на руки или до вычета НДФЛ?",
"Подтвердите вилку, найденную в описании, и ее базу: на руки или до вычета НДФЛ.")
status := NeedReadinessComplete
if len(missing) != 0 {
status = NeedReadinessIncomplete
}
return NeedReadinessReport{Status: status, MissingFields: missing}
}
func hasConfirmedNeedSkill(skills []NeedSkill) bool {
for _, skill := range skills {
if skill.Status == NeedItemConfirmed {
return true
}
}
return false
}
func confirmedNeedNeedsLocation(workFormats NeedValue[[]NeedWorkFormat]) bool {
if workFormats.Status != NeedValueConfirmed || workFormats.Value == nil {
return false
}
for _, format := range *workFormats.Value {
if format == NeedWorkFormatOffice || format == NeedWorkFormatHybrid {
return true
}
}
return false
}
func sameNeedContent(left, right NeedSnapshot) bool {
left.Version, right.Version = 0, 0
left.RequirementsVersion, right.RequirementsVersion = 0, 0
left.CreatedAt, right.CreatedAt = time.Time{}, time.Time{}
left.UpdatedAt, right.UpdatedAt = time.Time{}, time.Time{}
return reflect.DeepEqual(left, right)
}
type confirmedNeedProjection struct {
Specialization *SpecializationCode
Grade *GradeCode
RequiredSkills []confirmedNeedSkill
DesiredSkills []confirmedNeedSkill
Tasks []string
Domain *string
WorkFormats *[]NeedWorkFormat
Location *string
Salary *NeedSalaryRange
}
type confirmedNeedSkill struct {
Name string
TaxonomyCode *string
}
func sameConfirmedNeedRequirements(left, right NeedRequirements) bool {
return reflect.DeepEqual(confirmedNeedProjectionOf(left), confirmedNeedProjectionOf(right))
}
func confirmedNeedProjectionOf(requirements NeedRequirements) confirmedNeedProjection {
return confirmedNeedProjection{
Specialization: confirmedNeedValuePointer(requirements.Specialization),
Grade: confirmedNeedValuePointer(requirements.Grade),
RequiredSkills: confirmedNeedSkills(requirements.RequiredSkills),
DesiredSkills: confirmedNeedSkills(requirements.DesiredSkills),
Tasks: confirmedNeedTasks(requirements.Tasks),
Domain: confirmedNeedValuePointer(requirements.Domain),
WorkFormats: confirmedNeedValuePointer(requirements.WorkFormats),
Location: confirmedNeedValuePointer(requirements.Location),
Salary: confirmedNeedValuePointer(requirements.Salary),
}
}
func confirmedNeedValuePointer[T any](value NeedValue[T]) *T {
if value.Status != NeedValueConfirmed || value.Value == nil {
return nil
}
return cloneNeedPointer(value.Value)
}
func confirmedNeedSkills(skills []NeedSkill) []confirmedNeedSkill {
result := make([]confirmedNeedSkill, 0, len(skills))
for _, skill := range skills {
if skill.Status == NeedItemConfirmed {
result = append(result, confirmedNeedSkill{Name: skill.Name, TaxonomyCode: cloneNeedPointer(skill.TaxonomyCode)})
}
}
return result
}
func confirmedNeedTasks(tasks []NeedTask) []string {
result := make([]string, 0, len(tasks))
for _, task := range tasks {
if task.Status == NeedItemConfirmed {
result = append(result, task.Text)
}
}
return result
}
func validateNeedSnapshot(location string, snapshot NeedSnapshot) error {
switch {
case snapshot.ID == uuid.Nil || snapshot.OrganizationID == uuid.Nil:
return invalidNeed(location, "need and organization IDs must be set")
case snapshot.Version < 1 || snapshot.RequirementsVersion < 1 || snapshot.RequirementsVersion > snapshot.Version:
return invalidNeed(location, "versions must be positive and requirements_version cannot exceed version")
case !validNeedText(snapshot.Title, maxNeedTitleRunes):
return invalidNeedField(location, "/title", "must be 1 to 200 characters without surrounding whitespace or line breaks")
case snapshot.SourceText != nil && !validNeedLength(*snapshot.SourceText, maxNeedSourceTextRunes):
return invalidNeedField(location, "/source_text", "must be 1 to 10000 characters")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return invalidNeed(location, "timestamps must be set and ordered")
}
return validateNeedRequirements(location, snapshot.Version, snapshot.Requirements)
}
func validateNeedRequirements(location string, version int64, requirements NeedRequirements) error {
if requirements.RequiredSkills == nil || requirements.DesiredSkills == nil || requirements.Tasks == nil {
return invalidNeed(location, "requirement lists must be present")
}
if len(requirements.RequiredSkills) > maxNeedSkillItems || len(requirements.DesiredSkills) > maxNeedSkillItems || len(requirements.Tasks) > maxNeedTaskItems {
return invalidNeed(location, "requirement list exceeds its contract bound")
}
if err := validateNeedScalarRequirements(location, version, requirements); err != nil {
return err
}
if err := validateNeedSkillGroups(location, version, requirements); err != nil {
return err
}
return validateNeedTasks(location, version, requirements.Tasks)
}
func validateNeedScalarRequirements(location string, version int64, requirements NeedRequirements) error {
if err := validateNeedValue(location, "/requirements/specialization", version, requirements.Specialization,
func(value SpecializationCode) bool { return value.IsKnown() }, "must be a known specialization"); err != nil {
return err
}
if err := validateNeedValue(location, "/requirements/grade", version, requirements.Grade,
func(value GradeCode) bool { return value.IsKnown() }, "must be a known grade"); err != nil {
return err
}
if err := validateNeedValue(location, "/requirements/domain", version, requirements.Domain,
func(value string) bool { return validNeedText(value, maxNeedNameRunes) }, "must be 1 to 100 characters without surrounding whitespace or line breaks"); err != nil {
return err
}
if err := validateNeedValue(location, "/requirements/work_formats", version, requirements.WorkFormats,
validNeedWorkFormats, "must contain one to three unique known formats"); err != nil {
return err
}
if err := validateNeedValue(location, "/requirements/location", version, requirements.Location,
func(value string) bool { return validNeedText(value, maxNeedNameRunes) }, "must be 1 to 100 characters without surrounding whitespace or line breaks"); err != nil {
return err
}
if err := validateNeedValue(location, "/requirements/salary", version, requirements.Salary,
validNeedSalaryRange, "must be a valid monthly RUB range"); err != nil {
return err
}
return nil
}
func validateNeedSkillGroups(location string, version int64, requirements NeedRequirements) error {
type skillGroup struct {
name string
skills []NeedSkill
}
groups := []skillGroup{
{name: "required_skills", skills: requirements.RequiredSkills},
{name: "desired_skills", skills: requirements.DesiredSkills},
}
seenSkills := make(map[string]string, len(requirements.RequiredSkills)+len(requirements.DesiredSkills))
for _, group := range groups {
for index, skill := range group.skills {
pointer := "/requirements/" + group.name + "/" + strconv.Itoa(index)
if err := validateNeedSkill(location, version, pointer, skill); err != nil {
return err
}
if err := recordNeedSkillName(location, seenSkills, pointer+"/name", skill.Name); err != nil {
return err
}
}
}
return nil
}
func validateNeedTasks(location string, version int64, tasks []NeedTask) error {
for index, task := range tasks {
pointer := "/requirements/tasks/" + strconv.Itoa(index)
if !validNeedText(task.Text, maxNeedTaskRunes) {
return invalidNeedField(location, pointer+"/text", "must be 1 to 300 characters without surrounding whitespace or line breaks")
}
if task.Status != NeedItemConfirmed && task.Status != NeedItemExtracted {
return invalidNeedField(location, pointer+"/status", "must be confirmed or extracted")
}
if err := validateNeedItemSource(location, version, pointer+"/source", task.Status, task.Source); err != nil {
return err
}
}
return nil
}
func validateNeedValue[T any](location, pointer string, version int64, value NeedValue[T], valid func(T) bool, reason string) error {
switch value.Status {
case NeedValueUnknown:
if value.Value != nil || value.Source != nil {
return invalidNeedField(location, pointer, "unknown values must have null value and source")
}
return nil
case NeedValueConfirmed, NeedValueExtracted:
if value.Value == nil || value.Source == nil || !valid(*value.Value) {
return invalidNeedField(location, pointer+"/value", reason)
}
return validateNeedValueSource(location, version, pointer+"/source", value.Status, *value.Source)
default:
return invalidNeedField(location, pointer+"/status", "must be confirmed, extracted, or unknown")
}
}
func validateNeedSkill(location string, version int64, pointer string, skill NeedSkill) error {
if !validNeedText(skill.Name, maxNeedNameRunes) {
return invalidNeedField(location, pointer+"/name", "must be 1 to 100 characters without surrounding whitespace or line breaks")
}
if skill.TaxonomyCode != nil && !validNeedTaxonomyCode(*skill.TaxonomyCode) {
return invalidNeedField(location, pointer+"/taxonomy_code", "must be a valid taxonomy code")
}
if skill.Status != NeedItemConfirmed && skill.Status != NeedItemExtracted {
return invalidNeedField(location, pointer+"/status", "must be confirmed or extracted")
}
return validateNeedItemSource(location, version, pointer+"/source", skill.Status, skill.Source)
}
func validateNeedItemSource(location string, version int64, pointer string, status NeedItemStatus, source NeedValueSource) error {
valueStatus := NeedValueConfirmed
if status == NeedItemExtracted {
valueStatus = NeedValueExtracted
}
return validateNeedValueSource(location, version, pointer, valueStatus, source)
}
func validateNeedValueSource(location string, version int64, pointer string, status NeedValueStatus, source NeedValueSource) error {
if source.Quote != nil && !validNeedLength(*source.Quote, maxNeedQuoteRunes) {
return invalidNeedField(location, pointer+"/quote", "must be 1 to 300 characters")
}
if source.ExtractedInVersion != nil && (*source.ExtractedInVersion < 1 || *source.ExtractedInVersion > version) {
return invalidNeedField(location, pointer+"/extracted_in_version", "must name an existing need version")
}
if source.ExtractionVersion != nil && !validNeedVersionLabel(*source.ExtractionVersion) {
return invalidNeedField(location, pointer+"/extraction_version", "must be 1 to 64 ASCII letters, digits, dots, underscores, or hyphens")
}
if err := validateNeedSourceOrigin(location, pointer, status, source); err != nil {
return err
}
if status == NeedValueExtracted && source.Origin == NeedValueManual {
return invalidNeedField(location, pointer, "an unconfirmed value must have extracted provenance")
}
return nil
}
func validateNeedSourceOrigin(location, pointer string, status NeedValueStatus, source NeedValueSource) error {
switch source.Origin {
case NeedValueManual:
if status != NeedValueConfirmed || source.Quote != nil || source.ExtractedInVersion != nil || source.ExtractionVersion != nil {
return invalidNeedField(location, pointer, "manual provenance requires a confirmed value and null extraction fields")
}
case NeedValueExtractedFromText:
if source.ExtractedInVersion == nil || source.ExtractionVersion == nil {
return invalidNeedField(location, pointer, "text provenance requires source and extractor versions")
}
case NeedValueImported:
if source.ExtractionVersion == nil || source.Quote != nil || source.ExtractedInVersion != nil {
return invalidNeedField(location, pointer, "import provenance requires an extractor version and no text quote")
}
default:
return invalidNeedField(location, pointer+"/origin", "must be manual, extracted_from_text, or imported")
}
return nil
}
func recordNeedSkillName(location string, seen map[string]string, pointer, name string) error {
key := strings.ToLower(name)
if previous, exists := seen[key]; exists {
return invalidNeedField(location, pointer, "duplicates a skill at "+previous)
}
seen[key] = pointer
return nil
}
func validNeedWorkFormats(formats []NeedWorkFormat) bool {
if len(formats) < 1 || len(formats) > maxNeedWorkFormats {
return false
}
seen := make(map[NeedWorkFormat]struct{}, len(formats))
for _, format := range formats {
if !format.IsKnown() {
return false
}
if _, exists := seen[format]; exists {
return false
}
seen[format] = struct{}{}
}
return true
}
func validNeedSalaryRange(value NeedSalaryRange) bool {
if value.SalaryFrom < 1000 || value.SalaryFrom > 100000000 || value.SalaryFrom%1000 != 0 ||
value.SalaryTo < 1000 || value.SalaryTo > 100000000 || value.SalaryTo%1000 != 0 ||
value.Currency != "RUB" || value.Period != "month" || (value.TaxBasis != "net" && value.TaxBasis != "gross") ||
value.SalaryFrom >= value.SalaryTo {
return false
}
width := value.SalaryTo - value.SalaryFrom
sum := value.SalaryTo + value.SalaryFrom
return 20*width >= sum && 5*width <= sum
}
func validNeedTaxonomyCode(value string) bool {
if value == "" {
return false
}
for index, char := range value {
if index == 0 {
if !isASCIILowerOrDigit(char) {
return false
}
continue
}
if !isASCIILowerOrDigit(char) && char != '_' && char != '.' && char != '+' && char != '#' && char != '-' {
return false
}
}
return len(value) <= 64
}
func isASCIILowerOrDigit(value rune) bool {
return value >= 'a' && value <= 'z' || value >= '0' && value <= '9'
}
func validNeedVersionLabel(value string) bool {
if value == "" || len(value) > 64 {
return false
}
for _, char := range value {
if !isNeedVersionLabelCharacter(char) {
return false
}
}
return true
}
func isNeedVersionLabelCharacter(char rune) bool {
return char >= 'A' && char <= 'Z' || char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '.' || char == '_' || char == '-'
}
func validNeedText(value string, maxRunes int) bool {
if !validNeedLength(value, maxRunes) || strings.TrimSpace(value) != value {
return false
}
for _, char := range value {
if isNeedLineBreak(char) {
return false
}
}
return true
}
func validNeedLength(value string, maxRunes int) bool {
if !utf8.ValidString(value) {
return false
}
length := utf8.RuneCountInString(value)
return length > 0 && length <= maxRunes
}
func isNeedLineBreak(char rune) bool {
switch char {
case '\n', '\r', '\u0085', '\u2028', '\u2029':
return true
default:
return false
}
}
func invalidNeedField(location, pointer, reason string) error {
return fmt.Errorf("%s - invalid need field %s %s: %w", location, pointer, reason, ErrInvalidNeed)
}
func cloneNeedSnapshot(snapshot NeedSnapshot) NeedSnapshot {
cloned := snapshot
cloned.VacancyID = cloneNeedPointer(snapshot.VacancyID)
cloned.SourceText = cloneNeedPointer(snapshot.SourceText)
cloned.Requirements = cloneNeedRequirements(snapshot.Requirements)
return cloned
}
func cloneNeedRequirements(requirements NeedRequirements) NeedRequirements {
cloned := requirements
cloned.Specialization = cloneNeedValue(requirements.Specialization)
cloned.Grade = cloneNeedValue(requirements.Grade)
cloned.RequiredSkills = cloneNeedSkills(requirements.RequiredSkills)
cloned.DesiredSkills = cloneNeedSkills(requirements.DesiredSkills)
cloned.Tasks = cloneNeedTasks(requirements.Tasks)
cloned.Domain = cloneNeedValue(requirements.Domain)
cloned.WorkFormats = cloneNeedValue(requirements.WorkFormats)
cloned.Location = cloneNeedValue(requirements.Location)
cloned.Salary = cloneNeedValue(requirements.Salary)
return cloned
}
func cloneNeedValue[T any](value NeedValue[T]) NeedValue[T] {
result := value
if value.Value != nil {
var clonedValue T
switch typed := any(*value.Value).(type) {
case []NeedWorkFormat:
clonedValue = any(slices.Clone(typed)).(T)
default:
clonedValue = *value.Value
}
result.Value = &clonedValue
}
result.Source = cloneNeedSource(value.Source)
return result
}
func cloneNeedSource(source *NeedValueSource) *NeedValueSource {
if source == nil {
return nil
}
cloned := *source
cloned.Quote = cloneNeedPointer(source.Quote)
cloned.ExtractedInVersion = cloneNeedPointer(source.ExtractedInVersion)
cloned.ExtractionVersion = cloneNeedPointer(source.ExtractionVersion)
return &cloned
}
func cloneNeedSkills(skills []NeedSkill) []NeedSkill {
if skills == nil {
return nil
}
cloned := make([]NeedSkill, len(skills))
for index, skill := range skills {
cloned[index] = skill
cloned[index].TaxonomyCode = cloneNeedPointer(skill.TaxonomyCode)
cloned[index].Source = *cloneNeedSource(&skill.Source)
}
return cloned
}
func cloneNeedTasks(tasks []NeedTask) []NeedTask {
if tasks == nil {
return nil
}
cloned := make([]NeedTask, len(tasks))
for index, task := range tasks {
cloned[index] = task
cloned[index].Source = *cloneNeedSource(&task.Source)
}
return cloned
}
func cloneNeedPointer[T any](value *T) *T {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func (need Need) String() string { return redactedNeed }
func (need Need) GoString() string { return redactedNeed }
func (need Need) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedNeed)
}
func (need Need) LogValue() slog.Value { return slog.StringValue(redactedNeed) }
func (snapshot NeedSnapshot) String() string { return redactedNeed }
func (snapshot NeedSnapshot) GoString() string { return redactedNeed }
func (snapshot NeedSnapshot) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedNeed)
}
func (snapshot NeedSnapshot) LogValue() slog.Value { return slog.StringValue(redactedNeed) }
+370
View File
@@ -0,0 +1,370 @@
package domain
import (
"errors"
"fmt"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestNewNeedStartsIncompleteAtVersionOne(t *testing.T) {
snapshot := validNeedSnapshot()
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
if need.Version() != 1 || need.RequirementsVersion() != 1 {
t.Fatalf("version pair = %d/%d, want 1/1", need.Version(), need.RequirementsVersion())
}
readiness := need.Readiness()
wantFields := []NeedMissingFieldName{
NeedMissingSpecialization,
NeedMissingGrade,
NeedMissingRequiredSkills,
NeedMissingWorkFormats,
NeedMissingSalary,
}
gotFields := make([]NeedMissingFieldName, 0, len(readiness.MissingFields))
for _, field := range readiness.MissingFields {
gotFields = append(gotFields, field.Field)
}
if readiness.Status != NeedReadinessIncomplete || !reflect.DeepEqual(gotFields, wantFields) {
t.Fatalf("readiness = %+v, want incomplete fields %v", readiness, wantFields)
}
}
func TestNewNeedCanonicalizesTimestampsToStoragePrecision(t *testing.T) {
snapshot := validNeedSnapshot()
zone := time.FixedZone("test", 3*60*60)
snapshot.CreatedAt = time.Date(2026, 10, 7, 15, 0, 0, 123456789, zone)
snapshot.UpdatedAt = snapshot.CreatedAt.Add(time.Nanosecond)
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
want := snapshot.CreatedAt.UTC().Truncate(time.Microsecond)
if !need.CreatedAt().Equal(want) || !need.UpdatedAt().Equal(want) || need.CreatedAt().Location() != time.UTC {
t.Fatalf("canonical timestamps = %s / %s, want UTC %s", need.CreatedAt(), need.UpdatedAt(), want)
}
}
func TestNeedReadinessRequiresLocationOnlyForConfirmedOfficeOrHybrid(t *testing.T) {
snapshot := validNeedSnapshot()
formats := []NeedWorkFormat{NeedWorkFormatRemote}
snapshot.Requirements.WorkFormats = confirmedNeedValue(formats, manualNeedSource())
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed(remote) error = %v", err)
}
if containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) {
t.Fatal("remote-only need requires a location")
}
snapshot.Requirements.WorkFormats = confirmedNeedValue([]NeedWorkFormat{NeedWorkFormatOffice}, manualNeedSource())
need, err = NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed(office) error = %v", err)
}
if !containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) {
t.Fatal("confirmed office need is missing its location question")
}
snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{Status: NeedValueExtracted, Value: needPointer([]NeedWorkFormat{NeedWorkFormatOffice}), Source: textNeedSource(1)}
need, err = NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed(extracted office) error = %v", err)
}
if containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) {
t.Fatal("unconfirmed office suggestion cannot make location critical")
}
}
func TestNeedRevisePreservesVersionSemanticsAndNoOpOrder(t *testing.T) {
snapshot := validNeedSnapshot()
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
Status: NeedValueExtracted,
Value: needPointer(SpecializationBackend),
Source: textNeedSource(1),
}
current, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
proposal := current.Snapshot()
unchanged, changed, err := current.Revise(0, proposal)
if err != nil || changed || unchanged.Version() != 1 {
t.Fatalf("Revise(stale no-op) = version %d changed %v error %v, want unchanged version 1", unchanged.Version(), changed, err)
}
proposal.Title = "Payments team"
proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour)
if _, _, err := current.Revise(0, proposal); !errors.Is(err, ErrNeedVersionConflict) {
t.Fatalf("Revise(stale edit) error = %v, want version conflict", err)
}
proposal = current.Snapshot()
proposal.Title = "Payments team"
proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour)
titleOnly, changed, err := current.Revise(1, proposal)
if err != nil || !changed || titleOnly.Version() != 2 || titleOnly.RequirementsVersion() != 1 {
t.Fatalf("Revise(title) = version %d requirements %d changed %v error %v", titleOnly.Version(), titleOnly.RequirementsVersion(), changed, err)
}
proposal = titleOnly.Snapshot()
proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour)
proposal.Requirements.Specialization.Value = needPointer(SpecializationFrontend)
suggestionOnly, changed, err := titleOnly.Revise(2, proposal)
if err != nil || !changed || suggestionOnly.Version() != 3 || suggestionOnly.RequirementsVersion() != 1 {
t.Fatalf("Revise(suggestion) = version %d requirements %d changed %v error %v", suggestionOnly.Version(), suggestionOnly.RequirementsVersion(), changed, err)
}
proposal = suggestionOnly.Snapshot()
proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour)
proposal.Requirements.Specialization.Status = NeedValueConfirmed
confirmed, changed, err := suggestionOnly.Revise(3, proposal)
if err != nil || !changed || confirmed.Version() != 4 || confirmed.RequirementsVersion() != 4 {
t.Fatalf("Revise(confirm) = version %d requirements %d changed %v error %v", confirmed.Version(), confirmed.RequirementsVersion(), changed, err)
}
proposal = confirmed.Snapshot()
proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour)
proposal.Requirements.Specialization = NeedValue[SpecializationCode]{Status: NeedValueUnknown}
removed, changed, err := confirmed.Revise(4, proposal)
if err != nil || !changed || removed.Version() != 5 || removed.RequirementsVersion() != 5 {
t.Fatalf("Revise(remove confirmed) = version %d requirements %d changed %v error %v", removed.Version(), removed.RequirementsVersion(), changed, err)
}
}
func TestNeedIsNextVersionOfRejectsVersionOverflow(t *testing.T) {
maximum := int64(^uint64(0) >> 1)
snapshot := validNeedSnapshot()
snapshot.Version = maximum
snapshot.RequirementsVersion = maximum
current, err := RestoreNeed(snapshot)
if err != nil {
t.Fatalf("RestoreNeed(maximum version) error = %v", err)
}
candidateSnapshot := snapshot
candidateSnapshot.Version = 1
candidateSnapshot.RequirementsVersion = 1
candidate, err := RestoreNeed(candidateSnapshot)
if err != nil {
t.Fatalf("RestoreNeed(candidate) error = %v", err)
}
if current.IsNextVersionOf(candidate, maximum) {
t.Fatal("IsNextVersionOf() accepted an overflowed next version")
}
}
func TestNeedSnapshotIsDefensiveAndRedacted(t *testing.T) {
snapshot := validNeedSnapshot()
formats := []NeedWorkFormat{NeedWorkFormatRemote}
snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{
Status: NeedValueExtracted, Value: &formats, Source: textNeedSource(1),
}
snapshot.Requirements.RequiredSkills = []NeedSkill{{
Name: "Go", Status: NeedItemExtracted, Source: *textNeedSource(1),
}}
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
copiedSnapshot := need.Snapshot()
*copiedSnapshot.SourceText = "changed private text"
(*copiedSnapshot.Requirements.WorkFormats.Value)[0] = NeedWorkFormatOffice
*copiedSnapshot.Requirements.RequiredSkills[0].Source.Quote = "changed quote"
if got := *need.Snapshot().SourceText; got != "internal payments platform" {
t.Fatalf("source text changed through snapshot copy: %q", got)
}
if got := (*need.Snapshot().Requirements.WorkFormats.Value)[0]; got != NeedWorkFormatRemote {
t.Fatalf("work format changed through snapshot copy: %q", got)
}
if got := *need.Snapshot().Requirements.RequiredSkills[0].Source.Quote; got != "Go" {
t.Fatalf("quote changed through snapshot copy: %q", got)
}
for _, printed := range []string{fmt.Sprint(need), fmt.Sprintf("%+v", need), fmt.Sprintf("%#v", snapshot)} {
if strings.Contains(printed, "internal payments platform") || strings.Contains(printed, "changed private text") {
t.Fatalf("need formatting exposed private text: %q", printed)
}
}
}
func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) {
tests := []struct {
name string
change func(*NeedSnapshot)
}{
{name: "unknown has a value", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Specialization.Value = needPointer(SpecializationBackend)
}},
{name: "manual suggestion", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Grade = NeedValue[GradeCode]{Status: NeedValueExtracted, Value: needPointer(GradeJunior), Source: manualNeedSource()}
}},
{name: "future quote version", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Domain = NeedValue[string]{Status: NeedValueExtracted, Value: needPointer("payments"), Source: textNeedSource(2)}
}},
{name: "duplicate skills across lists", change: func(snapshot *NeedSnapshot) {
source := manualNeedSource()
snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: "Go", Status: NeedItemConfirmed, Source: *source}}
snapshot.Requirements.DesiredSkills = []NeedSkill{{Name: "go", Status: NeedItemConfirmed, Source: *source}}
}},
{name: "invalid salary width", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Salary = confirmedNeedValue(NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 109000, Currency: "RUB", Period: "month", TaxBasis: "gross"}, manualNeedSource())
}},
{name: "work formats not unique", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.WorkFormats = confirmedNeedValue([]NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatRemote}, manualNeedSource())
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
snapshot := validNeedSnapshot()
test.change(&snapshot)
if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) {
t.Fatalf("NewNeed(invalid) error = %v, want invalid need", err)
}
})
}
}
func TestNeedRejectsInvalidUTF8InContractText(t *testing.T) {
invalid := string([]byte{0xff})
tests := []struct {
name string
change func(*NeedSnapshot)
}{
{name: "title", change: func(snapshot *NeedSnapshot) { snapshot.Title = invalid }},
{name: "source text", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &invalid }},
{name: "provenance quote", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1),
}
snapshot.Requirements.Specialization.Source.Quote = &invalid
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
snapshot := validNeedSnapshot()
test.change(&snapshot)
if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) {
t.Fatalf("NewNeed() error = %v, want ErrInvalidNeed", err)
}
})
}
}
func TestNeedSalaryAcceptsContractBoundaries(t *testing.T) {
for _, test := range []struct {
from int64
to int64
}{
{from: 95000, to: 105000},
{from: 80000, to: 120000},
} {
snapshot := validNeedSnapshot()
snapshot.Requirements.Salary = confirmedNeedValue(NeedSalaryRange{
SalaryFrom: test.from, SalaryTo: test.to, Currency: "RUB", Period: "month", TaxBasis: "net",
}, manualNeedSource())
if _, err := NewNeed(snapshot); err != nil {
t.Fatalf("NewNeed(salary %d-%d) error = %v", test.from, test.to, err)
}
}
}
func TestNeedValueSourceManualAndTextRules(t *testing.T) {
manual := manualNeedSource()
if err := validateNeedValueSource("test", 1, "/source", NeedValueConfirmed, *manual); err != nil {
t.Fatalf("validate manual source error = %v", err)
}
text := textNeedSource(1)
if err := validateNeedValueSource("test", 1, "/source", NeedValueExtracted, *text); err != nil {
t.Fatalf("validate text suggestion source error = %v", err)
}
}
func TestNeedReadinessOnlyCountsConfirmedRequirements(t *testing.T) {
snapshot := validNeedSnapshot()
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1),
}
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
readiness := need.Readiness()
if readiness.MissingFields[0].Field != NeedMissingSpecialization || readiness.MissingFields[0].Reason != NeedMissingUnconfirmed ||
readiness.MissingFields[0].Question != "Подтвердите специализацию, найденную в описании." {
t.Fatalf("specialization readiness = %+v", readiness.MissingFields[0])
}
snapshot = validNeedSnapshot()
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1),
}
snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: "Go", Status: NeedItemExtracted, Source: *textNeedSource(1)}}
snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{
Status: NeedValueExtracted, Value: needPointer([]NeedWorkFormat{NeedWorkFormatRemote}), Source: textNeedSource(1),
}
snapshot.Requirements.Salary = NeedValue[NeedSalaryRange]{
Status: NeedValueExtracted,
Value: needPointer(NeedSalaryRange{SalaryFrom: 80000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"}),
Source: textNeedSource(1),
}
need, err = NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed(extracted criticals) error = %v", err)
}
readiness = need.Readiness()
for _, field := range readiness.MissingFields {
if field.Field == NeedMissingSpecialization || field.Field == NeedMissingRequiredSkills || field.Field == NeedMissingWorkFormats || field.Field == NeedMissingSalary {
if field.Reason != NeedMissingUnconfirmed {
t.Errorf("field %s reason = %s, want unconfirmed", field.Field, field.Reason)
}
}
}
}
func validNeedSnapshot() NeedSnapshot {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
sourceText := "internal payments platform"
return NeedSnapshot{
ID: uuid.Must(uuid.NewV7()), OrganizationID: uuid.Must(uuid.NewV7()),
Title: "Backend payments", SourceText: &sourceText, Version: 1, RequirementsVersion: 1,
Requirements: EmptyNeedRequirements(), CreatedAt: now, UpdatedAt: now,
}
}
func manualNeedSource() *NeedValueSource {
return &NeedValueSource{Origin: NeedValueManual}
}
func textNeedSource(version int64) *NeedValueSource {
quote := "Go"
extractor := "need-rules.2026-10.1"
return &NeedValueSource{
Origin: NeedValueExtractedFromText, Quote: &quote,
ExtractedInVersion: &version, ExtractionVersion: &extractor,
}
}
func confirmedNeedValue[T any](value T, source *NeedValueSource) NeedValue[T] {
return NeedValue[T]{Status: NeedValueConfirmed, Value: &value, Source: source}
}
func needPointer[T any](value T) *T { return &value }
func containsNeedField(fields []NeedMissingField, field NeedMissingFieldName) bool {
for _, candidate := range fields {
if candidate.Field == field {
return true
}
}
return false
}
+50
View File
@@ -0,0 +1,50 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrNeedNotFound reports that the need does not exist in organizationID.
ErrNeedNotFound = errors.New("organization need not found")
// ErrNeedAlreadyExists reports that a need with the supplied ID is already
// stored. Creation idempotency is handled by the application usecase.
ErrNeedAlreadyExists = errors.New("organization need already exists")
// ErrNeedVersionConflict reports a stale expected need version. The
// surrounding transaction remains safe to roll back and the API maps the
// conflict to its current 412 contract.
ErrNeedVersionConflict = errors.New("organization need changed concurrently")
)
// NeedRepositories exposes tenant-scoped need storage bound to one
// UnitOfWork transaction.
type NeedRepositories interface {
Needs() NeedRepository
}
// NeedRepository stores the current organization need and its immutable
// version snapshots. Every operation scopes by both organization and need ID.
type NeedRepository interface {
// Create inserts version 1 and its initial snapshot in the surrounding
// transaction. The organization must already exist.
Create(ctx context.Context, need domain.Need) error
// Get returns the current snapshot in organizationID, or ErrNeedNotFound.
Get(ctx context.Context, organizationID, needID uuid.UUID) (domain.Need, error)
// GetVersion returns one immutable historical snapshot scoped to its
// organization and need. It returns ErrNeedNotFound for a missing version.
GetVersion(ctx context.Context, organizationID, needID uuid.UUID, version int64) (domain.Need, error)
// Save appends the single next version and atomically advances the current
// pointer when it still equals expectedVersion. The caller's transaction
// rolls back both writes if either write fails.
Save(ctx context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error
}
@@ -55,6 +55,7 @@ type UnitOfWork interface {
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
NeedRepositories
CompanyQuotas() CompanyQuotaRepository
AssessmentBankRepositories
Policies() PolicyRepository