feat(invitations): add organization invitation drafts with salary range rules

This commit is contained in:
shira committed 2026-10-09 14:28:36 +03:00
1 parent 28337d84cb
commit bd23c839fd
36 files changed
+7018 -83

No files matched your search

@@ -0,0 +1,443 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
_ outbound.InvitationRepository = invitationRepository{}
_ outbound.InvitationCreationResultRepository = invitationRepository{}
)
// maxInvitationCreationResultBytes bounds the stored original response of a
// create: the terms plus the alias and the fixed fields.
const maxInvitationCreationResultBytes = 163840
func (unit *UnitOfWork) Invitations() outbound.InvitationRepository {
return invitationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) InvitationCreationResults() outbound.InvitationCreationResultRepository {
return invitationRepository{queries: unit.queries}
}
type invitationRepository struct {
queries *sqlc.Queries
}
func (repository invitationRepository) Create(
ctx context.Context,
invitation domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Create"
stored := invitation.Stored()
if stored.State != string(domain.InvitationDraft) || stored.Version != 1 || stored.TermsVersion != 1 {
return fmt.Errorf("%s - creation must store a draft at version 1: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, invitation, event, 1); err != nil {
return err
}
period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays)
if err != nil {
return err
}
if err := repository.queries.InsertInvitation(ctx, sqlc.InsertInvitationParams{
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need),
State: stored.State, Version: stored.Version, TermsVersion: stored.TermsVersion,
ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()),
CreatedBy: pgUUID(stored.CreatedBy), CreatedAt: pgTime(stored.CreatedAt), UpdatedAt: pgTime(stored.UpdatedAt),
}); err != nil {
return fmt.Errorf("%s - insert invitation: %w", location, mapInvitationError(err))
}
if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil {
return err
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) Get(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.Get"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.ReadInvitation(ctx, sqlc.ReadInvitationParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
})
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
}
return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), organizationID)
}
func (repository invitationRepository) GetForUpdate(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.GetForUpdate"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
if _, err := repository.queries.LockInvitation(ctx, sqlc.LockInvitationParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
}); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err))
}
invitation, err := repository.Get(ctx, organizationID, invitationID)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err)
}
return invitation, nil
}
func (repository invitationRepository) GetTermsVersion(
ctx context.Context,
organizationID, invitationID uuid.UUID,
version int64,
) (domain.InvitationTerms, error) {
const location = "invitationRepository.GetTermsVersion"
if organizationID == uuid.Nil || invitationID == uuid.Nil || version < 1 {
return domain.InvitationTerms{}, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := repository.queries.ReadInvitationTermsVersion(ctx, sqlc.ReadInvitationTermsVersionParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), Version: version,
})
if err != nil {
return domain.InvitationTerms{}, fmt.Errorf("%s - read terms version: %w", location, mapInvitationNoRows(err))
}
terms, err := domain.DecodeInvitationTerms([]byte(encoded))
if err != nil {
return domain.InvitationTerms{}, fmt.Errorf("%s - restore terms: %w", location, err)
}
return terms, nil
}
func (repository invitationRepository) List(
ctx context.Context,
query outbound.InvitationListQuery,
) (outbound.InvitationPage, error) {
const location = "invitationRepository.List"
if query.OrganizationID == uuid.Nil {
return outbound.InvitationPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation)
}
if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize {
return outbound.InvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation)
}
params := sqlc.ListInvitationsParams{OrganizationID: pgUUID(query.OrganizationID), RowLimit: query.Limit + 1}
if query.After != nil {
after := *query.After
if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.CreatedAt) {
return outbound.InvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation)
}
params.AfterCreatedAt = pgTime(after.CreatedAt)
params.AfterInvitationID = pgUUID(after.InvitationID)
}
rows, err := repository.queries.ListInvitations(ctx, params)
if err != nil {
return outbound.InvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err))
}
page := outbound.InvitationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]domain.Invitation, 0, len(rows))
for _, row := range rows {
invitation, err := restoreInvitationRow(location, row, query.OrganizationID)
if err != nil {
return outbound.InvitationPage{}, err
}
page.Items = append(page.Items, invitation)
}
return page, nil
}
func (repository invitationRepository) SaveDraft(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
termsChanged bool,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.SaveDraft"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 {
return fmt.Errorf("%s - the next version must follow the expected one: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
return err
}
period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays)
if err != nil {
return err
}
_, err = repository.queries.AdvanceInvitationDraft(ctx, sqlc.AdvanceInvitationDraftParams{
NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need),
ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()),
TermsVersion: stored.TermsVersion, NextVersion: stored.Version, UpdatedAt: pgTime(stored.UpdatedAt),
OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - advance draft: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - advance draft: %w", location, mapInvitationError(err))
}
if termsChanged {
if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil {
return err
}
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) NeedVersionExists(
ctx context.Context,
organizationID, needID uuid.UUID,
requirementsVersion int64,
) (bool, error) {
const location = "invitationRepository.NeedVersionExists"
if organizationID == uuid.Nil || needID == uuid.Nil || requirementsVersion < 1 {
return false, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation)
}
found, err := repository.queries.InvitationNeedVersionExists(ctx, sqlc.InvitationNeedVersionExistsParams{
OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID), RequirementsVersion: requirementsVersion,
})
if err != nil {
return false, fmt.Errorf("%s - look up need version: %w", location, mapInvitationError(err))
}
return found, nil
}
func (repository invitationRepository) SaveCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result domain.OrganizationInvitationView,
) error {
const location = "invitationRepository.SaveCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := encodeInvitationCreationResult(result)
if err != nil {
return fmt.Errorf("%s - encode response: %w", location, err)
}
if err := repository.queries.SaveInvitationCreationResult(ctx, sqlc.SaveInvitationCreationResultParams{
ScopeHash: scope[:], Snapshot: encoded,
}); err != nil {
return fmt.Errorf("%s - store response: %w", location, mapInvitationError(err))
}
return nil
}
func (repository invitationRepository) GetCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (domain.OrganizationInvitationView, error) {
const location = "invitationRepository.GetCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := repository.queries.GetInvitationCreationResult(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound
}
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read response: %w", location, mapInvitationError(err))
}
return decodeInvitationCreationResult(location, []byte(encoded))
}
// insertEventPrerequisites checks that the audit event describes the version
// that the caller is about to store.
func (repository invitationRepository) insertEventPrerequisites(
location string,
invitation domain.Invitation,
event domain.InvitationEvent,
version int64,
) error {
if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() ||
event.Version != version || event.TermsVersion != invitation.TermsVersion() || event.ActorID == uuid.Nil ||
!validStoredInvitationTime(event.OccurredAt) {
return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation)
}
return nil
}
func (repository invitationRepository) insertTermsVersion(
ctx context.Context,
location string,
stored domain.StoredInvitation,
version int64,
at time.Time,
) error {
encoded, err := domain.EncodeInvitationTerms(stored.Terms)
if err != nil {
return fmt.Errorf("%s - encode terms: %w", location, err)
}
if err := repository.queries.InsertInvitationTermsVersion(ctx, sqlc.InsertInvitationTermsVersionParams{
InvitationID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), Version: version,
Terms: encoded, SalaryFrom: stored.Terms.Salary.SalaryFrom, SalaryTo: stored.Terms.Salary.SalaryTo,
SalaryCurrency: stored.Terms.Salary.Currency, SalaryPeriod: stored.Terms.Salary.Period,
SalaryTaxBasis: stored.Terms.Salary.TaxBasis, CreatedAt: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - append terms version: %w", location, mapInvitationError(err))
}
return nil
}
func (repository invitationRepository) insertEvent(ctx context.Context, location string, event domain.InvitationEvent) error {
fields := make([]string, 0, len(event.ChangedFields))
for _, field := range event.ChangedFields {
fields = append(fields, string(field))
}
slices.Sort(fields)
if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{
ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID),
Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: pgUUID(event.ActorID),
ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt),
}); err != nil {
return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err))
}
return nil
}
func restoreInvitationRow(location string, row sqlc.ListInvitationsRow, organizationID uuid.UUID) (domain.Invitation, error) {
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.CreatedBy.Valid || !row.PolicyVersionID.Valid ||
!row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != organizationID {
return domain.Invitation{}, fmt.Errorf("%s - invitation row has invalid scope or metadata: %w", location, domain.ErrInvalidInvitation)
}
terms, err := domain.DecodeInvitationTerms([]byte(row.Terms))
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - restore terms: %w", location, err)
}
stored := domain.StoredInvitation{
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
CandidateID: uuid.UUID(row.CandidateID.Bytes), State: row.State, Version: row.Version,
TermsVersion: row.TermsVersion, Terms: terms, ResponsePeriodDays: int32(row.ResponsePeriodDays),
PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), SalaryRaiseUsed: row.SalaryRaiseUsed,
CreatedBy: uuid.UUID(row.CreatedBy.Bytes), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
ResponseDeadlineAt: optionalTime(row.ResponseDeadlineAt), DeliveredAt: optionalTime(row.DeliveredAt),
ViewedAt: optionalTime(row.ViewedAt), RespondedAt: optionalTime(row.RespondedAt),
}
if row.ExpiryReason.Valid {
reason := row.ExpiryReason.String
stored.ExpiryReason = &reason
}
if row.NeedID.Valid != row.NeedRequirementsVersion.Valid {
return domain.Invitation{}, fmt.Errorf("%s - need link is incomplete: %w", location, domain.ErrInvalidInvitation)
}
if row.NeedID.Valid {
stored.Need = &domain.InvitationNeedRef{NeedID: uuid.UUID(row.NeedID.Bytes), RequirementsVersion: row.NeedRequirementsVersion.Int64}
}
invitation, err := domain.RestoreInvitation(stored)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - restore invitation: %w", location, err)
}
return invitation, nil
}
func encodeInvitationCreationResult(result domain.OrganizationInvitationView) ([]byte, error) {
if err := validateInvitationCreationResult(result); err != nil {
return nil, err
}
encoded, err := json.Marshal(result)
if err != nil {
return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - marshal: %w", err)
}
if len(encoded) > maxInvitationCreationResultBytes {
return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - response exceeds %d bytes: %w", maxInvitationCreationResultBytes, domain.ErrInvalidInvitation)
}
return encoded, nil
}
func decodeInvitationCreationResult(location string, encoded []byte) (domain.OrganizationInvitationView, error) {
var result domain.OrganizationInvitationView
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&result); err != nil || decoder.More() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationCreationResult(result); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err)
}
return result, nil
}
func validateInvitationCreationResult(result domain.OrganizationInvitationView) error {
if result.ID == uuid.Nil || result.OrganizationID == uuid.Nil || !domain.IsCandidateViewPseudonym(result.CandidateHandle) {
return fmt.Errorf("postgres.validateInvitationCreationResult - identity is incomplete: %w", domain.ErrInvalidInvitation)
}
if err := result.Terms.Validate(); err != nil {
return fmt.Errorf("postgres.validateInvitationCreationResult - validate terms: %w", err)
}
return nil
}
func invitationNeedID(need *domain.InvitationNeedRef) pgtype.UUID {
if need == nil {
return pgtype.UUID{}
}
return pgUUID(need.NeedID)
}
func invitationNeedVersion(need *domain.InvitationNeedRef) pgtype.Int8 {
if need == nil {
return pgtype.Int8{}
}
return pgtype.Int8{Int64: need.RequirementsVersion, Valid: true}
}
func validStoredInvitationTime(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0
}
func mapInvitationNoRows(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ErrInvitationNotFound
}
return mapInvitationError(err)
}
func mapInvitationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitations_organization_fkey" {
return fmt.Errorf("postgres.mapInvitationError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
}
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_creation_results_idempotency_fkey" {
return fmt.Errorf("postgres.mapInvitationError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// invitationResponsePeriodParam converts the period to its smallint column.
// The domain allows only the periods of the product policy, so a value out of
// range is an invalid invitation, never a silently truncated one.
func invitationResponsePeriodParam(location string, days int32) (int16, error) {
if days < 1 || days > math.MaxInt16 {
return 0, fmt.Errorf("%s - response period is out of range: %w", location, domain.ErrInvalidInvitation)
}
return int16(days), nil
}
@@ -0,0 +1,557 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitations.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceInvitationDraft = `-- name: AdvanceInvitationDraft :one
UPDATE invitations
SET
need_id = $1,
need_requirements_version = $2,
response_period_days = $3,
policy_version_id = $4,
terms_version = $5,
version = $6,
updated_at = $7
WHERE
organization_id = $8
AND id = $9
AND state = 'draft'
AND version = $10
AND $6::bigint = $10::bigint + 1
RETURNING id
`
type AdvanceInvitationDraftParams struct {
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
TermsVersion int64
NextVersion int64
UpdatedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The conditional update is the compare-and-swap of a draft: it applies only
// to a draft whose version is still the one the caller read, and advances the
// version by one. No row is returned when it lost a race or the invitation
// left the draft state.
func (q *Queries) AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, advanceInvitationDraft,
arg.NeedID,
arg.NeedRequirementsVersion,
arg.ResponsePeriodDays,
arg.PolicyVersionID,
arg.TermsVersion,
arg.NextVersion,
arg.UpdatedAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const getInvitationCreationResult = `-- name: GetInvitationCreationResult :one
SELECT snapshot::text AS snapshot
FROM invitation_creation_results
WHERE scope_hash = $1
`
func (q *Queries) GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
row := q.db.QueryRow(ctx, getInvitationCreationResult, scopeHash)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertInvitation = `-- name: InsertInvitation :exec
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,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13
)
`
type InsertInvitationParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The invitation row, its first terms version, and its first audit event are
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
func (q *Queries) InsertInvitation(ctx context.Context, arg InsertInvitationParams) error {
_, err := q.db.Exec(ctx, insertInvitation,
arg.ID,
arg.OrganizationID,
arg.CandidateID,
arg.NeedID,
arg.NeedRequirementsVersion,
arg.State,
arg.Version,
arg.TermsVersion,
arg.ResponsePeriodDays,
arg.PolicyVersionID,
arg.CreatedBy,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertInvitationEvent = `-- name: InsertInvitationEvent :exec
INSERT INTO invitation_events (
id,
invitation_id,
organization_id,
version,
terms_version,
kind,
actor_id,
changed_fields,
occurred_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8::text [],
$9
)
`
type InsertInvitationEventParams struct {
ID pgtype.UUID
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
TermsVersion int64
Kind string
ActorID pgtype.UUID
ChangedFields []string
OccurredAt pgtype.Timestamptz
}
func (q *Queries) InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error {
_, err := q.db.Exec(ctx, insertInvitationEvent,
arg.ID,
arg.InvitationID,
arg.OrganizationID,
arg.Version,
arg.TermsVersion,
arg.Kind,
arg.ActorID,
arg.ChangedFields,
arg.OccurredAt,
)
return err
}
const insertInvitationTermsVersion = `-- name: InsertInvitationTermsVersion :exec
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,
$10
)
`
type InsertInvitationTermsVersionParams struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
Terms []byte
SalaryFrom int64
SalaryTo int64
SalaryCurrency string
SalaryPeriod string
SalaryTaxBasis string
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error {
_, err := q.db.Exec(ctx, insertInvitationTermsVersion,
arg.InvitationID,
arg.OrganizationID,
arg.Version,
arg.Terms,
arg.SalaryFrom,
arg.SalaryTo,
arg.SalaryCurrency,
arg.SalaryPeriod,
arg.SalaryTaxBasis,
arg.CreatedAt,
)
return err
}
const invitationNeedVersionExists = `-- name: InvitationNeedVersionExists :one
SELECT EXISTS (
SELECT 1
FROM organization_need_versions
WHERE
organization_id = $1
AND need_id = $2
AND version = $3::bigint
AND snapshot ->> 'requirements_version' = $3::bigint::text
) AS found
`
type InvitationNeedVersionExistsParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
RequirementsVersion int64
}
// A requirements version that a need of the organization has had is the
// version number of a stored snapshot whose own requirements version is that
// number, so a later edit that only renamed the need is not accepted.
func (q *Queries) InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error) {
row := q.db.QueryRow(ctx, invitationNeedVersionExists, arg.OrganizationID, arg.NeedID, arg.RequirementsVersion)
var found bool
err := row.Scan(&found)
return found, err
}
const listInvitations = `-- name: ListInvitations :many
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
WHERE
invitation.organization_id = $1
AND (
$2::timestamptz IS NULL
OR (invitation.created_at, invitation.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY invitation.created_at DESC, invitation.id DESC
LIMIT $4
`
type ListInvitationsParams struct {
OrganizationID pgtype.UUID
AfterCreatedAt pgtype.Timestamptz
AfterInvitationID pgtype.UUID
RowLimit int32
}
type ListInvitationsRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
}
// One bounded newest-first page. Both the organization scope and the tuple
// cursor are applied before the limit.
func (q *Queries) ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error) {
rows, err := q.db.Query(ctx, listInvitations,
arg.OrganizationID,
arg.AfterCreatedAt,
arg.AfterInvitationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListInvitationsRow
for rows.Next() {
var i ListInvitationsRow
if err := rows.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockInvitation = `-- name: LockInvitation :one
SELECT id
FROM invitations
WHERE
organization_id = $1
AND id = $2
FOR UPDATE
`
type LockInvitationParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
// Takes the row lock of one invitation. It is a statement of its own, ahead of
// ReadInvitation, because a locking read that joins the terms table is
// re-checked against the new row version after a wait and then pairs the
// updated terms_version with the terms row it fetched before the wait, which
// finds nothing. Once the lock is held, the following read sees the committed
// state and no writer can change it.
func (q *Queries) LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockInvitation, arg.OrganizationID, arg.InvitationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const readInvitation = `-- name: ReadInvitation :one
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
WHERE
invitation.organization_id = $1
AND invitation.id = $2
`
type ReadInvitationParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
type ReadInvitationRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
}
// Read one current invitation with its terms snapshot. Both the organization
// and the invitation scope the row, so another organization's identifier
// finds nothing.
func (q *Queries) ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error) {
row := q.db.QueryRow(ctx, readInvitation, arg.OrganizationID, arg.InvitationID)
var i ReadInvitationRow
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
)
return i, err
}
const readInvitationTermsVersion = `-- name: ReadInvitationTermsVersion :one
SELECT terms::text AS terms
FROM invitation_terms_versions
WHERE
organization_id = $1
AND invitation_id = $2
AND version = $3
`
type ReadInvitationTermsVersionParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
Version int64
}
// Read one historical terms version of one invitation of one organization.
func (q *Queries) ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error) {
row := q.db.QueryRow(ctx, readInvitationTermsVersion, arg.OrganizationID, arg.InvitationID, arg.Version)
var terms string
err := row.Scan(&terms)
return terms, err
}
const saveInvitationCreationResult = `-- name: SaveInvitationCreationResult :exec
INSERT INTO invitation_creation_results (scope_hash, snapshot)
VALUES ($1, $2::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveInvitationCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
func (q *Queries) SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error {
_, err := q.db.Exec(ctx, saveInvitationCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
@@ -570,6 +570,58 @@ type IdempotencyRecord struct {
ExpiresAt pgtype.Timestamptz
}
type Invitation struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
}
type InvitationCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type InvitationEvent struct {
ID pgtype.UUID
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
TermsVersion int64
Kind string
ActorID pgtype.UUID
ChangedFields []string
OccurredAt pgtype.Timestamptz
}
type InvitationTermsVersion struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
Terms []byte
SalaryFrom int64
SalaryTo int64
SalaryCurrency string
SalaryPeriod string
SalaryTaxBasis string
CreatedAt pgtype.Timestamptz
}
type MailQuotaReservation struct {
ID pgtype.UUID
DeliveryID pgtype.UUID
@@ -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 update is the compare-and-swap of a draft: it applies only
// to a draft whose version is still the one the caller read, and advances the
// version by one. No row is returned when it lost a race or the invitation
// left the draft state.
AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, 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
@@ -291,6 +296,7 @@ type Querier interface {
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
@@ -461,6 +467,12 @@ type Querier interface {
// for it.
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
// The invitation row, its first terms version, and its first audit event are
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
@@ -518,6 +530,10 @@ type Querier interface {
InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error)
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// A requirements version that a need of the organization has had is the
// version number of a stored snapshot whose own requirements version is that
// number, so a later edit that only renamed the need is not accepted.
InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error)
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
@@ -607,6 +623,9 @@ type Querier interface {
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// One bounded newest-first page. Both the organization scope and the tuple
// cursor are applied before the limit.
ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error)
// List only the authenticated recipient's rows, optionally narrowed to one
// organization context. The caller resolves current source visibility before
// returning content.
@@ -730,6 +749,13 @@ type Querier interface {
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Takes the row lock of one invitation. It is a statement of its own, ahead of
// ReadInvitation, because a locking read that joins the terms table is
// re-checked against the new row version after a wait and then pairs the
// updated terms_version with the terms row it fetched before the wait, which
// finds nothing. Once the lock is held, the following read sees the committed
// state and no writer can change it.
LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -843,6 +869,12 @@ type Querier interface {
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one current invitation with its terms snapshot. Both the organization
// and the invitation scope the row, so another organization's identifier
// finds nothing.
ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error)
// Read one historical terms version of one invitation of one organization.
ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// Reads a full owner-scoped record. Object values are identifiers only.
@@ -937,6 +969,7 @@ type Querier interface {
// compares it with the policy captured in the assigned result.
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the