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,349 @@
-- +goose Up
-- Invitation storage. An invitation names one candidate for one organization.
-- Its terms live in immutable numbered versions: every change of the terms
-- appends the next version, and the invitation row only points at the current
-- one. The salary range is kept in typed columns next to the JSON snapshot, so
-- the database itself refuses a range that breaks the money rules. Amounts are
-- whole rubles, as in the API contract; there are no minor units and no
-- floating-point columns.
--
-- The candidate column is internal. API responses show the candidate only
-- through the organization-scoped alias that the server derives on every read.
CREATE TABLE invitations (
id uuid NOT NULL,
organization_id uuid NOT NULL,
candidate_id uuid NOT NULL,
need_id uuid,
need_requirements_version bigint,
state text NOT NULL,
expiry_reason text,
version bigint NOT NULL,
terms_version bigint NOT NULL,
response_period_days smallint NOT NULL,
-- The product policy that allowed the chosen response period.
policy_version_id uuid NOT NULL,
response_deadline_at timestamptz,
salary_raise_used boolean NOT NULL DEFAULT FALSE,
created_by uuid NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
delivered_at timestamptz,
viewed_at timestamptz,
responded_at timestamptz,
CONSTRAINT invitations_pkey PRIMARY KEY (id),
CONSTRAINT invitations_organization_id_id_key UNIQUE (organization_id, id),
CONSTRAINT invitations_organization_fkey FOREIGN KEY (organization_id)
REFERENCES organizations (id) ON DELETE RESTRICT,
-- A candidate with invitations cannot be deleted until a deletion
-- procedure settles them, like an account with consent evidence.
CONSTRAINT invitations_candidate_fkey FOREIGN KEY (candidate_id)
REFERENCES users (id) ON DELETE RESTRICT,
CONSTRAINT invitations_created_by_fkey FOREIGN KEY (created_by)
REFERENCES users (id) ON DELETE RESTRICT,
CONSTRAINT invitations_policy_version_fkey FOREIGN KEY (policy_version_id)
REFERENCES policy_versions (id) ON DELETE RESTRICT,
-- The need link is informational and must name a requirements version
-- that the need of the same organization has stored.
CONSTRAINT invitations_need_fkey FOREIGN KEY (organization_id, need_id)
REFERENCES organization_needs (organization_id, id) ON DELETE RESTRICT,
CONSTRAINT invitations_need_version_fkey FOREIGN KEY (
organization_id, need_id, need_requirements_version
) REFERENCES organization_need_versions (organization_id, need_id, version)
ON DELETE RESTRICT,
CONSTRAINT invitations_need_pair CHECK (
(need_id IS NULL) = (need_requirements_version IS NULL)
),
CONSTRAINT invitations_state_known CHECK (
state IN (
'draft', 'delivered', 'viewed', 'counter', 'accepted',
'interview_scheduled', 'interviewed', 'negotiation',
'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn',
'cancelled_by_candidate'
)
),
CONSTRAINT invitations_expiry_reason CHECK (
(state = 'expired') = (expiry_reason IS NOT NULL)
AND (
expiry_reason IS NULL
OR expiry_reason IN ('invitation_timeout', 'negotiation_timeout')
)
),
CONSTRAINT invitations_version_positive CHECK (version > 0),
CONSTRAINT invitations_terms_version_range CHECK (
terms_version > 0 AND terms_version <= version
),
CONSTRAINT invitations_response_period CHECK (
response_period_days IN (3, 7, 14)
),
-- The deadline starts with the first delivery and is set together with it.
CONSTRAINT invitations_deadline_with_delivery CHECK (
(response_deadline_at IS NULL) = (delivered_at IS NULL)
AND (response_deadline_at IS NULL OR response_deadline_at > delivered_at)
),
-- A draft is invisible to the candidate and has no delivery, view,
-- answer, or raise yet.
CONSTRAINT invitations_draft_is_unsent CHECK (
state <> 'draft'
OR (
delivered_at IS NULL
AND viewed_at IS NULL
AND responded_at IS NULL
AND NOT salary_raise_used
)
),
CONSTRAINT invitations_timestamps CHECK (updated_at >= created_at)
);
CREATE TABLE invitation_terms_versions (
invitation_id uuid NOT NULL,
organization_id uuid NOT NULL,
version bigint NOT NULL,
terms jsonb NOT NULL,
salary_from bigint NOT NULL,
salary_to bigint NOT NULL,
salary_currency text NOT NULL,
salary_period text NOT NULL,
salary_tax_basis text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT invitation_terms_versions_pkey PRIMARY KEY (invitation_id, version),
CONSTRAINT invitation_terms_versions_invitation_fkey FOREIGN KEY (
organization_id, invitation_id
) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT,
CONSTRAINT invitation_terms_versions_version_positive CHECK (version > 0),
-- Money rules (PRD FR13) in integer arithmetic: positive bounds that are
-- multiples of 1000, A < B, and a width 2 * (B - A) / (A + B) from 10% to
-- 40%, that is 20 * (B - A) >= A + B and 5 * (B - A) <= A + B. The bounds
-- are capped at 100 000 000 rubles, so no product overflows.
CONSTRAINT invitation_terms_versions_salary_bounds CHECK (
salary_from BETWEEN 1000 AND 100000000
AND salary_to BETWEEN 1000 AND 100000000
AND salary_from % 1000 = 0
AND salary_to % 1000 = 0
AND salary_from < salary_to
),
CONSTRAINT invitation_terms_versions_salary_width CHECK (
20 * (salary_to - salary_from) >= salary_from + salary_to
AND 5 * (salary_to - salary_from) <= salary_from + salary_to
),
CONSTRAINT invitation_terms_versions_salary_basis CHECK (
salary_currency = 'RUB'
AND salary_period = 'month'
AND salary_tax_basis IN ('net', 'gross')
),
-- The snapshot is a complete object whose salary equals the typed columns.
-- jsonb::text adds structural whitespace, so the size bound leaves room.
CONSTRAINT invitation_terms_versions_snapshot_shape CHECK (
jsonb_typeof(terms) = 'object'
AND terms ?& ARRAY[
'role_title', 'specialization', 'grade', 'offer_type', 'tasks',
'team', 'tech_stack', 'work_formats', 'location',
'communication_method', 'salary', 'package'
]
AND jsonb_typeof(terms -> 'salary') = 'object'
AND CASE
WHEN jsonb_typeof(terms #> '{salary,salary_from}') = 'number'
AND jsonb_typeof(terms #> '{salary,salary_to}') = 'number'
THEN (terms #>> '{salary,salary_from}') = salary_from::text
AND (terms #>> '{salary,salary_to}') = salary_to::text
ELSE FALSE
END
AND (terms #>> '{salary,currency}') = salary_currency
AND (terms #>> '{salary,period}') = salary_period
AND (terms #>> '{salary,tax_basis}') = salary_tax_basis
AND octet_length(terms::text) <= 131072
)
);
-- The current terms version must exist for the same invitation. Deferral lets
-- creation insert the invitation and its first terms in one transaction.
ALTER TABLE invitations
ADD CONSTRAINT invitations_current_terms_fkey
FOREIGN KEY (id, terms_version)
REFERENCES invitation_terms_versions (invitation_id, version)
DEFERRABLE INITIALLY DEFERRED;
-- The changed fields of an audit event are a duplicate-free subset of the
-- editable parts of a draft.
-- +goose StatementBegin
CREATE FUNCTION invitation_changed_fields_are_valid(fields text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
fields <@ ARRAY['terms', 'need', 'response_period_days']::text []
AND array_position(fields, NULL) IS NULL
AND fields = ARRAY(
SELECT DISTINCT field COLLATE "C"
FROM unnest(fields) AS field
ORDER BY field COLLATE "C"
);
$$;
-- +goose StatementEnd
-- One audit event per committed invitation version. The event names the
-- actor and what changed, never the content: the terms are in their own
-- immutable versions.
CREATE TABLE invitation_events (
id uuid NOT NULL,
invitation_id uuid NOT NULL,
organization_id uuid NOT NULL,
version bigint NOT NULL,
terms_version bigint NOT NULL,
kind text NOT NULL,
actor_id uuid NOT NULL,
changed_fields text [] NOT NULL,
occurred_at timestamptz NOT NULL,
CONSTRAINT invitation_events_pkey PRIMARY KEY (id),
CONSTRAINT invitation_events_version_key UNIQUE (invitation_id, version),
CONSTRAINT invitation_events_invitation_fkey FOREIGN KEY (
organization_id, invitation_id
) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT,
CONSTRAINT invitation_events_actor_fkey FOREIGN KEY (actor_id)
REFERENCES users (id) ON DELETE RESTRICT,
CONSTRAINT invitation_events_terms_version_fkey FOREIGN KEY (
invitation_id, terms_version
) REFERENCES invitation_terms_versions (invitation_id, version)
ON DELETE RESTRICT,
CONSTRAINT invitation_events_version_positive CHECK (
version > 0 AND terms_version > 0 AND terms_version <= version
),
CONSTRAINT invitation_events_kind_known CHECK (
kind IN ('draft_created', 'draft_updated')
),
CONSTRAINT invitation_events_creation_is_first CHECK (
(kind = 'draft_created') = (version = 1)
),
CONSTRAINT invitation_events_changed_fields CHECK (
invitation_changed_fields_are_valid(changed_fields)
)
);
-- Original response of an idempotent create, kept beside the generic
-- idempotency record and removed with it after the 24-hour replay window.
-- The live invitation is intentionally not a foreign key.
CREATE TABLE invitation_creation_results (
scope_hash bytea NOT NULL,
snapshot jsonb NOT NULL,
CONSTRAINT invitation_creation_results_pkey PRIMARY KEY (scope_hash),
CONSTRAINT invitation_creation_results_idempotency_fkey FOREIGN KEY (
scope_hash
) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
CONSTRAINT invitation_creation_results_scope_hash_sha256 CHECK (
octet_length(scope_hash) = 32
),
CONSTRAINT invitation_creation_results_snapshot_bounded CHECK (
jsonb_typeof(snapshot) = 'object'
AND octet_length(snapshot::text) <= 196608
)
);
-- Newest-first list of one organization.
CREATE INDEX invitations_organization_created_idx
ON invitations (organization_id, created_at DESC, id DESC);
-- Pair rules of the organization and the candidate, such as the pause after a
-- decline, read the invitations of one pair.
CREATE INDEX invitations_organization_candidate_idx
ON invitations (organization_id, candidate_id, created_at DESC);
-- The candidate's inbox reads the invitations that were delivered to them.
CREATE INDEX invitations_candidate_delivered_idx
ON invitations (candidate_id, delivered_at DESC, id DESC)
WHERE delivered_at IS NOT NULL;
-- Identity and history rules. An invitation is never deleted, its identity
-- never changes, every committed change advances the version by one, a terms
-- version advances by at most one, and a raise or a deadline is never undone.
-- TRUNCATE remains available to reset isolated integration databases.
-- +goose StatementBegin
CREATE FUNCTION invitations_guard_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.id IS DISTINCT FROM OLD.id
OR NEW.organization_id IS DISTINCT FROM OLD.organization_id
OR NEW.candidate_id IS DISTINCT FROM OLD.candidate_id
OR NEW.created_by IS DISTINCT FROM OLD.created_by
OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_identity_immutable',
TABLE = 'invitations',
MESSAGE = 'invitation identity is immutable';
END IF;
IF NEW.version <> OLD.version + 1
OR (NEW.terms_version <> OLD.terms_version AND NEW.terms_version <> OLD.terms_version + 1) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_version_step',
TABLE = 'invitations',
MESSAGE = 'invitation versions advance by exactly one step';
END IF;
IF (OLD.salary_raise_used AND NOT NEW.salary_raise_used)
OR (OLD.delivered_at IS NOT NULL AND (
NEW.delivered_at IS DISTINCT FROM OLD.delivered_at
OR NEW.response_deadline_at IS DISTINCT FROM OLD.response_deadline_at
OR NEW.response_period_days IS DISTINCT FROM OLD.response_period_days
)) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_history_immutable',
TABLE = 'invitations',
MESSAGE = 'a raise, a delivery, and a deadline are never undone';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER invitations_guard_update
BEFORE UPDATE ON invitations
FOR EACH ROW EXECUTE FUNCTION invitations_guard_update();
-- Terms versions and audit events are append-only.
-- +goose StatementBegin
CREATE FUNCTION invitations_refuse_history_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = TG_TABLE_NAME || '_immutable',
TABLE = TG_TABLE_NAME,
MESSAGE = 'invitation history is append-only: add a new version instead';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER invitations_refuse_delete
BEFORE DELETE ON invitations
FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change();
CREATE TRIGGER invitation_terms_versions_immutable
BEFORE UPDATE OR DELETE ON invitation_terms_versions
FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change();
CREATE TRIGGER invitation_events_immutable
BEFORE UPDATE OR DELETE ON invitation_events
FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change();
-- +goose Down
-- A rollback must not silently remove stored invitations or their history.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM invitations) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_retained',
TABLE = 'invitations',
MESSAGE = 'invitations must be resolved before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TABLE invitation_creation_results;
DROP TABLE invitation_events;
ALTER TABLE invitations DROP CONSTRAINT invitations_current_terms_fkey;
DROP TABLE invitation_terms_versions;
DROP TABLE invitations;
DROP FUNCTION invitation_changed_fields_are_valid(text []);
DROP FUNCTION invitations_refuse_history_change();
DROP FUNCTION invitations_guard_update();
+224
View File
@@ -0,0 +1,224 @@
-- 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.
-- 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 (
sqlc.arg(id),
sqlc.arg(organization_id),
sqlc.arg(candidate_id),
sqlc.narg(need_id),
sqlc.narg(need_requirements_version),
sqlc.arg(state),
sqlc.arg(version),
sqlc.arg(terms_version),
sqlc.arg(response_period_days),
sqlc.arg(policy_version_id),
sqlc.arg(created_by),
sqlc.arg(created_at),
sqlc.arg(updated_at)
);
-- 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 (
sqlc.arg(invitation_id),
sqlc.arg(organization_id),
sqlc.arg(version),
sqlc.arg(terms)::jsonb,
sqlc.arg(salary_from),
sqlc.arg(salary_to),
sqlc.arg(salary_currency),
sqlc.arg(salary_period),
sqlc.arg(salary_tax_basis),
sqlc.arg(created_at)
);
-- name: InsertInvitationEvent :exec
INSERT INTO invitation_events (
id,
invitation_id,
organization_id,
version,
terms_version,
kind,
actor_id,
changed_fields,
occurred_at
) VALUES (
sqlc.arg(id),
sqlc.arg(invitation_id),
sqlc.arg(organization_id),
sqlc.arg(version),
sqlc.arg(terms_version),
sqlc.arg(kind),
sqlc.arg(actor_id),
sqlc.arg(changed_fields)::text [],
sqlc.arg(occurred_at)
);
-- Read one current invitation with its terms snapshot. Both the organization
-- and the invitation scope the row, so another organization's identifier
-- finds nothing.
-- 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 = sqlc.arg(organization_id)
AND invitation.id = sqlc.arg(invitation_id);
-- 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.
-- name: LockInvitation :one
SELECT id
FROM invitations
WHERE
organization_id = sqlc.arg(organization_id)
AND id = sqlc.arg(invitation_id)
FOR UPDATE;
-- Read one historical terms version of one invitation of one organization.
-- name: ReadInvitationTermsVersion :one
SELECT terms::text AS terms
FROM invitation_terms_versions
WHERE
organization_id = sqlc.arg(organization_id)
AND invitation_id = sqlc.arg(invitation_id)
AND version = sqlc.arg(version);
-- One bounded newest-first page. Both the organization scope and the tuple
-- cursor are applied before the limit.
-- 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 = sqlc.arg(organization_id)
AND (
sqlc.narg(after_created_at)::timestamptz IS NULL
OR (invitation.created_at, invitation.id) < (
sqlc.narg(after_created_at)::timestamptz,
sqlc.narg(after_invitation_id)::uuid
)
)
ORDER BY invitation.created_at DESC, invitation.id DESC
LIMIT sqlc.arg(row_limit);
-- 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.
-- name: AdvanceInvitationDraft :one
UPDATE invitations
SET
need_id = sqlc.narg(need_id),
need_requirements_version = sqlc.narg(need_requirements_version),
response_period_days = sqlc.arg(response_period_days),
policy_version_id = sqlc.arg(policy_version_id),
terms_version = sqlc.arg(terms_version),
version = sqlc.arg(next_version),
updated_at = sqlc.arg(updated_at)
WHERE
organization_id = sqlc.arg(organization_id)
AND id = sqlc.arg(invitation_id)
AND state = 'draft'
AND version = sqlc.arg(expected_version)
AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1
RETURNING id;
-- 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.
-- name: InvitationNeedVersionExists :one
SELECT EXISTS (
SELECT 1
FROM organization_need_versions
WHERE
organization_id = sqlc.arg(organization_id)
AND need_id = sqlc.arg(need_id)
AND version = sqlc.arg(requirements_version)::bigint
AND snapshot ->> 'requirements_version' = sqlc.arg(requirements_version)::bigint::text
) AS found;
-- name: SaveInvitationCreationResult :exec
INSERT INTO invitation_creation_results (scope_hash, snapshot)
VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot;
-- name: GetInvitationCreationResult :one
SELECT snapshot::text AS snapshot
FROM invitation_creation_results
WHERE scope_hash = sqlc.arg(scope_hash);