339 lines
19 KiB
Go
339 lines
19 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strconv"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
)
|
|
|
|
const (
|
|
// invitationMigrationVersion creates the invitation tables.
|
|
invitationMigrationVersion = 37
|
|
invitationRetainedState = "invitations_retained"
|
|
)
|
|
|
|
type invitationStorageFixture struct {
|
|
ctx context.Context
|
|
transactor *postgresadapter.Transactor
|
|
organization domain.Organization
|
|
owner domain.User
|
|
candidate domain.User
|
|
policyID domain.PolicyVersionID
|
|
now time.Time
|
|
}
|
|
|
|
func invitationStorageTerms() domain.InvitationTerms {
|
|
none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided}
|
|
return domain.InvitationTerms{
|
|
RoleTitle: "Storage role", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle,
|
|
OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Store the draft"}, Team: "Storage team",
|
|
TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote},
|
|
CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail},
|
|
Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"},
|
|
Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none},
|
|
}
|
|
}
|
|
|
|
func newInvitationStorageFixture(ctx context.Context, t *testing.T, databaseURL string) (invitationStorageFixture, *pgxpool.Pool) {
|
|
t.Helper()
|
|
pool := newPoolFor(ctx, t, databaseURL)
|
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
|
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
|
|
organizations := organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now}
|
|
owner := organizations.employer(t, "storage-owner@example.test")
|
|
organization := organizations.create(t, owner, organizations.completeProfile(t, "Invitation storage company"), now)
|
|
candidate := identity.createUser(t, "storage-candidate@example.test", domain.ScenarioCandidate, now.Add(-time.Hour))
|
|
seeded, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx)
|
|
if err != nil {
|
|
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
|
}
|
|
return invitationStorageFixture{
|
|
ctx: ctx, transactor: postgresadapter.NewTransactor(pool), organization: organization, owner: owner,
|
|
candidate: candidate, policyID: seeded.Version.ID(), now: now,
|
|
}, pool
|
|
}
|
|
|
|
// draft stores a new draft through the repository in its own transaction.
|
|
func (fixture invitationStorageFixture) draft(t *testing.T) domain.Invitation {
|
|
t.Helper()
|
|
invitationID, err := uuid.NewV7()
|
|
if err != nil {
|
|
t.Fatalf("NewV7() error = %v", err)
|
|
}
|
|
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
|
|
ID: invitationID, OrganizationID: fixture.organization.ID(), CandidateID: fixture.candidate.ID, ActorID: fixture.owner.ID,
|
|
PolicyVersionID: fixture.policyID, At: fixture.now,
|
|
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewInvitationDraft() error = %v", err)
|
|
}
|
|
event, err := draft.DraftEvent(fixture.owner.ID, nil)
|
|
if err != nil {
|
|
t.Fatalf("DraftEvent() error = %v", err)
|
|
}
|
|
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return unit.Invitations().Create(ctx, draft, event)
|
|
}); err != nil {
|
|
t.Fatalf("store the draft: %v", err)
|
|
}
|
|
return draft
|
|
}
|
|
|
|
func TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates(t *testing.T) {
|
|
env := bootstrap(t, postgresService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
fixture, _ := newInvitationStorageFixture(ctx, t, databaseURL)
|
|
draft := fixture.draft(t)
|
|
|
|
read := func(work func(unit outbound.UnitOfWork) error) error {
|
|
return fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return work(unit) })
|
|
}
|
|
var stored domain.Invitation
|
|
if err := read(func(unit outbound.UnitOfWork) error {
|
|
var err error
|
|
stored, err = unit.Invitations().Get(ctx, fixture.organization.ID(), draft.ID())
|
|
return err
|
|
}); err != nil {
|
|
t.Fatalf("Get() error = %v", err)
|
|
}
|
|
if got, want := stored.Snapshot(), draft.Snapshot(); got.Version != want.Version || !got.Terms.Equal(want.Terms) || !got.CreatedAt.Equal(want.CreatedAt) ||
|
|
stored.CandidateID() != fixture.candidate.ID || stored.PolicyVersionID() != fixture.policyID {
|
|
t.Fatalf("stored draft = %+v, want the one that was saved", got)
|
|
}
|
|
// Another organization finds nothing.
|
|
err := read(func(unit outbound.UnitOfWork) error {
|
|
_, err := unit.Invitations().Get(ctx, uuid.New(), draft.ID())
|
|
return err
|
|
})
|
|
if !errors.Is(err, outbound.ErrInvitationNotFound) {
|
|
t.Fatalf("Get(another organization) error = %v, want ErrInvitationNotFound", err)
|
|
}
|
|
|
|
content := draft.DraftContent()
|
|
content.Terms.Salary.SalaryTo = 150_000
|
|
revised, changed, err := draft.ReviseDraft(content, fixture.policyID, fixture.now.Add(time.Minute))
|
|
if err != nil {
|
|
t.Fatalf("ReviseDraft() error = %v", err)
|
|
}
|
|
event, err := revised.DraftEvent(fixture.owner.ID, changed)
|
|
if err != nil {
|
|
t.Fatalf("DraftEvent() error = %v", err)
|
|
}
|
|
// A save from a version that is not current is refused and stores nothing.
|
|
err = read(func(unit outbound.UnitOfWork) error {
|
|
return unit.Invitations().SaveDraft(ctx, 7, revised, true, event)
|
|
})
|
|
if err == nil {
|
|
t.Fatal("SaveDraft(from version 7) succeeded")
|
|
}
|
|
if err := read(func(unit outbound.UnitOfWork) error {
|
|
return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event)
|
|
}); err != nil {
|
|
t.Fatalf("SaveDraft() error = %v", err)
|
|
}
|
|
// The same save again lost the race: the stored draft moved on.
|
|
err = read(func(unit outbound.UnitOfWork) error {
|
|
return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event)
|
|
})
|
|
if !errors.Is(err, outbound.ErrInvitationVersionConflict) {
|
|
t.Fatalf("second SaveDraft() error = %v, want ErrInvitationVersionConflict", err)
|
|
}
|
|
|
|
if err := read(func(unit outbound.UnitOfWork) error {
|
|
first, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
second, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 2)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if first.Salary.SalaryTo != 140_000 || second.Salary.SalaryTo != 150_000 {
|
|
t.Errorf("terms versions end at %d and %d, want 140000 and 150000", first.Salary.SalaryTo, second.Salary.SalaryTo)
|
|
}
|
|
if _, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 3); !errors.Is(err, outbound.ErrInvitationNotFound) {
|
|
t.Errorf("GetTermsVersion(3) error = %v, want ErrInvitationNotFound", err)
|
|
}
|
|
if _, err := unit.Invitations().GetTermsVersion(ctx, uuid.New(), draft.ID(), 1); !errors.Is(err, outbound.ErrInvitationNotFound) {
|
|
t.Errorf("GetTermsVersion(another organization) error = %v, want ErrInvitationNotFound", err)
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("read terms versions: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestInvitationTablesRefuseMoneyAndHistoryViolations(t *testing.T) {
|
|
env := bootstrap(t, postgresService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
applyMigrations(ctx, t, databaseURL)
|
|
fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL)
|
|
draft := fixture.draft(t)
|
|
id := draft.ID()
|
|
snapshot := func(from, to int64, basis string) string {
|
|
return `{"role_title":"x","specialization":"backend","grade":"middle","offer_type":"full_time","tasks":["x"],"team":"x",` +
|
|
`"tech_stack":["Go"],"work_formats":["remote"],"location":null,"communication_method":{"channel":"email","details":null},` +
|
|
`"salary":{"salary_from":` + strconv.FormatInt(from, 10) + `,"salary_to":` + strconv.FormatInt(to, 10) + `,"currency":"RUB","period":"month","tax_basis":"` + basis + `"},` +
|
|
`"package":{"bonus":{"status":"not_provided"},"equipment":{"status":"not_provided"},"training":{"status":"not_provided"},"health_insurance":{"status":"not_provided"}}}`
|
|
}
|
|
insertTerms := func(version int64, from, to int64, currency, period, basis string, terms string) error {
|
|
_, err := pool.Exec(ctx, `INSERT INTO invitation_terms_versions (
|
|
invitation_id, organization_id, version, terms, salary_from, salary_to, salary_currency, salary_period, salary_tax_basis, created_at
|
|
) VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, now())`,
|
|
id, fixture.organization.ID(), version, terms, from, to, currency, period, basis)
|
|
return err
|
|
}
|
|
|
|
// The money rules hold in the database for any writer.
|
|
assertPgError(t, "A equal to B", insertTerms(2, 100000, 100000, "RUB", "month", "net", snapshot(100000, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds")
|
|
assertPgError(t, "A off the step", insertTerms(2, 100500, 140000, "RUB", "month", "net", snapshot(100500, 140000, "net")), checkViolation, "invitation_terms_versions_salary_bounds")
|
|
assertPgError(t, "A of zero", insertTerms(2, 0, 100000, "RUB", "month", "net", snapshot(0, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds")
|
|
assertPgError(t, "width below 10 percent", insertTerms(2, 95000, 104000, "RUB", "month", "net", snapshot(95000, 104000, "net")), checkViolation, "invitation_terms_versions_salary_width")
|
|
assertPgError(t, "width above 40 percent", insertTerms(2, 80000, 121000, "RUB", "month", "net", snapshot(80000, 121000, "net")), checkViolation, "invitation_terms_versions_salary_width")
|
|
assertPgError(t, "foreign currency", insertTerms(2, 100000, 140000, "USD", "month", "net", snapshot(100000, 140000, "net")), checkViolation, "invitation_terms_versions_salary_basis")
|
|
assertPgError(t, "unknown base", insertTerms(2, 100000, 140000, "RUB", "month", "pre-tax", snapshot(100000, 140000, "pre-tax")), checkViolation, "invitation_terms_versions_salary_basis")
|
|
assertPgError(t, "snapshot that disagrees with the columns", insertTerms(2, 100000, 140000, "RUB", "month", "net", snapshot(100000, 150000, "net")), checkViolation, "invitation_terms_versions_snapshot_shape")
|
|
assertPgError(t, "snapshot without a term", insertTerms(2, 100000, 140000, "RUB", "month", "net", `{"salary":{"salary_from":100000,"salary_to":140000,"currency":"RUB","period":"month","tax_basis":"net"}}`), checkViolation, "invitation_terms_versions_snapshot_shape")
|
|
// The exact boundaries are accepted by the same rules, as new versions of
|
|
// the same invitation.
|
|
if err := insertTerms(2, 95000, 105000, "RUB", "month", "gross", snapshot(95000, 105000, "gross")); err != nil {
|
|
t.Fatalf("insert the 10 percent range: %v", err)
|
|
}
|
|
if err := insertTerms(3, 80000, 120000, "RUB", "month", "gross", snapshot(80000, 120000, "gross")); err != nil {
|
|
t.Fatalf("insert the 40 percent range: %v", err)
|
|
}
|
|
_, err := pool.Exec(ctx, `DELETE FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 2`, id)
|
|
assertPgError(t, "delete of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable")
|
|
|
|
// Terms versions and audit events are append-only.
|
|
_, err = pool.Exec(ctx, `UPDATE invitation_terms_versions SET salary_to = 150000 WHERE invitation_id = $1 AND version = 1`, id)
|
|
assertPgError(t, "update of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable")
|
|
_, err = pool.Exec(ctx, `UPDATE invitation_events SET kind = 'draft_updated' WHERE invitation_id = $1`, id)
|
|
assertPgError(t, "update of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable")
|
|
_, err = pool.Exec(ctx, `DELETE FROM invitation_events WHERE invitation_id = $1`, id)
|
|
assertPgError(t, "delete of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable")
|
|
|
|
// The invitation keeps its identity, steps its version by one, and is
|
|
// never deleted.
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET candidate_id = $2, version = version + 1 WHERE id = $1`, id, fixture.owner.ID)
|
|
assertPgError(t, "change of the candidate", err, privacyIntegrityViolation, "invitations_identity_immutable")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET version = version + 2 WHERE id = $1`, id)
|
|
assertPgError(t, "version that skips a step", err, privacyIntegrityViolation, "invitations_version_step")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET terms_version = 3, version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "terms version that skips a step", err, privacyIntegrityViolation, "invitations_version_step")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 5, version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "response period outside the policy options", err, checkViolation, "invitations_response_period")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "delivery without a deadline", err, checkViolation, "invitations_deadline_with_delivery")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), response_deadline_at = now() + interval '7 days', version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "delivery of a draft", err, checkViolation, "invitations_draft_is_unsent")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'expired', version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "expiry without a reason", err, checkViolation, "invitations_expiry_reason")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'sent', version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "the internal sending step as a state", err, checkViolation, "invitations_state_known")
|
|
_, err = pool.Exec(ctx, `DELETE FROM invitations WHERE id = $1`, id)
|
|
assertPgError(t, "delete of an invitation", err, privacyIntegrityViolation, "invitations_immutable")
|
|
|
|
// A delivered invitation keeps its deadline.
|
|
if _, err := pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', delivered_at = '2026-10-09T10:00:00Z',
|
|
response_deadline_at = '2026-10-16T10:00:00Z', version = version + 1 WHERE id = $1`, id); err != nil {
|
|
t.Fatalf("deliver the invitation: %v", err)
|
|
}
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = '2026-10-30T10:00:00Z', version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "move of the deadline", err, privacyIntegrityViolation, "invitations_history_immutable")
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 14, version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "change of the period after delivery", err, privacyIntegrityViolation, "invitations_history_immutable")
|
|
if _, err := pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = true, version = version + 1 WHERE id = $1`, id); err != nil {
|
|
t.Fatalf("record the raise: %v", err)
|
|
}
|
|
_, err = pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = false, version = version + 1 WHERE id = $1`, id)
|
|
assertPgError(t, "undoing the raise", err, privacyIntegrityViolation, "invitations_history_immutable")
|
|
|
|
// An invitation links only to a need of its own organization, and its
|
|
// current terms version must exist when the transaction commits.
|
|
foreignOrganization := organizationFixture{ctx: ctx, pool: pool, identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: fixture.now},
|
|
transactor: fixture.transactor, now: fixture.now}
|
|
otherOwner := foreignOrganization.employer(t, "storage-other-owner@example.test")
|
|
other := foreignOrganization.create(t, otherOwner, foreignOrganization.completeProfile(t, "Other storage company"), fixture.now)
|
|
needID := uuid.New()
|
|
_, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, need_requirements_version, state, version, terms_version,
|
|
response_period_days, policy_version_id, created_by, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, 1, 'draft', 1, 1, 7, $5, $6, now(), now())`,
|
|
uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID)
|
|
assertPgError(t, "link to an unknown need", err, privacyForeignKeyViolation, "invitations_need_fkey")
|
|
_, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, state, version, terms_version,
|
|
response_period_days, policy_version_id, created_by, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, 'draft', 1, 1, 7, $5, $6, now(), now())`,
|
|
uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID)
|
|
assertPgError(t, "need without a requirements version", err, checkViolation, "invitations_need_pair")
|
|
_, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, state, version, terms_version,
|
|
response_period_days, policy_version_id, created_by, created_at, updated_at)
|
|
VALUES ($1, $2, $3, 'draft', 1, 1, 7, $4, $5, now(), now())`,
|
|
uuid.New(), other.ID(), fixture.candidate.ID, fixture.policyID, otherOwner.ID)
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) || pgError.Code != privacyForeignKeyViolation || pgError.ConstraintName != "invitations_current_terms_fkey" {
|
|
t.Fatalf("invitation without its first terms version error = %v, want a deferred violation of invitations_current_terms_fkey", err)
|
|
}
|
|
}
|
|
|
|
func TestInvitationMigrationRollbackKeepsStoredInvitations(t *testing.T) {
|
|
env := bootstrap(t, postgresService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
migrator := newMigrator(t, databaseURL)
|
|
if _, err := migrator.Up(ctx); err != nil {
|
|
t.Fatalf("Up() error = %v", err)
|
|
}
|
|
fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL)
|
|
rollBackAboveVersion(ctx, t, migrator, invitationMigrationVersion)
|
|
fixture.draft(t)
|
|
|
|
_, err := migrator.DownOne(ctx)
|
|
assertPgError(t, "DownOne() with a stored invitation", err, privacyIntegrityViolation, invitationRetainedState)
|
|
statuses, err := migrator.Status(ctx)
|
|
if err != nil {
|
|
t.Fatalf("Status() error = %v", err)
|
|
}
|
|
for _, status := range statuses {
|
|
if status.Version == invitationMigrationVersion && !status.Applied {
|
|
t.Fatal("the invitation migration was rolled back despite a stored invitation")
|
|
}
|
|
}
|
|
|
|
// Once the rows are gone the rollback succeeds and the tables disappear.
|
|
if _, err := pool.Exec(ctx, `TRUNCATE invitation_creation_results, invitation_events, invitation_terms_versions, invitations`); err != nil {
|
|
t.Fatalf("clear the invitation tables: %v", err)
|
|
}
|
|
result, err := migrator.DownOne(ctx)
|
|
if err != nil || result.Version != invitationMigrationVersion {
|
|
t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationMigrationVersion)
|
|
}
|
|
var remaining int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name LIKE 'invitation%'`).Scan(&remaining); err != nil || remaining != 0 {
|
|
t.Fatalf("invitation tables left after the rollback: %d, %v", remaining, err)
|
|
}
|
|
if _, err := migrator.Up(ctx); err != nil {
|
|
t.Fatalf("Up() after the rollback error = %v", err)
|
|
}
|
|
}
|