feat(accounts): add consent settings and organization management

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:00:39 +03:00
1 parent 24638d46d2
commit 391af7a1ef
83 files changed
+10198 -613

No files matched your search

@@ -0,0 +1,211 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type accountDeletionRequestRepository struct {
queries *sqlc.Queries
}
func (unit *UnitOfWork) AccountDeletionRequests() outbound.AccountDeletionRequests {
return accountDeletionRequestRepository{queries: unit.queries}
}
func (repository accountDeletionRequestRepository) CreateOrGet(
ctx context.Context,
request domain.AccountDeletionRequest,
) (domain.AccountDeletionRequest, bool, error) {
if request.IsZero() {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - request is not initialized: %w", domain.ErrInvalidConsent)
}
row, err := repository.queries.CreateAccountDeletionRequest(ctx, sqlc.CreateAccountDeletionRequestParams{
ID: pgUUID(request.ID()),
SubjectID: pgUUID(request.SubjectID()),
RequestedAt: pgTime(request.RequestedAt()),
})
if err == nil {
stored, err := accountDeletionRequestFromRow(row.ID, row.SubjectID, row.Status, row.RequestedAt)
return stored, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - insert request: %w", mapConsentError(err))
}
activeRow, err := repository.queries.GetActiveAccountDeletionRequest(ctx, pgUUID(request.SubjectID()))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - concurrent request was not readable: %w", outbound.ErrTransactionConflict)
}
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - select active request: %w", mapConsentError(err))
}
stored, err := accountDeletionRequestFromRow(activeRow.ID, activeRow.SubjectID, activeRow.Status, activeRow.RequestedAt)
return stored, false, err
}
func accountDeletionRequestFromRow(id, subjectID pgtype.UUID, status string, requestedAt pgtype.Timestamptz) (domain.AccountDeletionRequest, error) {
if !id.Valid || !subjectID.Valid || !requestedAt.Valid {
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - required column is null: %w", domain.ErrInvalidConsent)
}
request, err := domain.RestoreAccountDeletionRequest(id.Bytes, subjectID.Bytes, status, requestedAt.Time)
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - restore request: %w", err)
}
return request, nil
}
type consentRevocationEffects struct {
queries *sqlc.Queries
}
func (unit *UnitOfWork) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
return consentRevocationEffects{queries: unit.queries}
}
var _ outbound.ConsentRevocationEffects = consentRevocationEffects{}
func (effects consentRevocationEffects) Apply(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
if revocation.IsZero() || len(records) == 0 {
return fmt.Errorf("consentRevocationEffects.Apply - revocation and affected records are required: %w", domain.ErrInvalidConsent)
}
for _, record := range records {
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
return fmt.Errorf("consentRevocationEffects.Apply - record scope does not match revocation: %w", domain.ErrInvalidConsent)
}
}
if revocation.Purpose() == domain.ConsentPurposePublication {
if err := effects.closePublication(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err)
}
}
if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err)
}
return nil
}
func (effects consentRevocationEffects) closePublication(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
const location = "consentRevocationEffects.closePublication"
recordIDs := make([]pgtype.UUID, 0, len(records))
for _, record := range records {
if record.Purpose() == domain.ConsentPurposePublication {
recordIDs = append(recordIDs, pgUUID(record.ID()))
}
}
if len(recordIDs) == 0 {
return fmt.Errorf("%s - revoked C2 record IDs are required: %w", location, domain.ErrInvalidConsent)
}
row, err := effects.queries.LockCandidatePublicationForConsentRevocation(ctx, sqlc.LockCandidatePublicationForConsentRevocationParams{
UserID: pgUUID(revocation.SubjectID()), ConsentRecordIds: recordIDs,
})
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return fmt.Errorf("%s - close publication: %w", location, mapConsentError(err))
}
if !row.Valid {
return fmt.Errorf("%s - query returned no closing time: %w", location, domain.ErrInvalidVisibility)
}
event, err := domain.NewConsentRevokedPublicationEvent(revocation.SubjectID(), row.Time)
if err != nil {
return fmt.Errorf("%s - build publication privacy event: %w", location, err)
}
if err := effects.queries.InsertCandidatePrivacyEvent(ctx, sqlc.InsertCandidatePrivacyEventParams{
ID: pgUUID(event.ID()),
UserID: pgUUID(event.UserID()),
Kind: string(event.Kind()),
OccurredAt: pgTime(event.OccurredAt()),
Fields: event.Fields().Codes(),
ConsentRecordID: pgtype.UUID{},
OrganizationID: pgtype.UUID{},
}); err != nil {
return fmt.Errorf("%s - record publication privacy event: %w", location, mapConsentError(err))
}
return nil
}
type consentRevocationPayload struct {
RevocationID uuid.UUID `json:"revocation_id"`
RecordID uuid.UUID `json:"record_id"`
SubjectID uuid.UUID `json:"subject_id"`
Purpose domain.ConsentPurpose `json:"purpose"`
Source domain.ConsentRevocationSource `json:"source"`
RevokedAt time.Time `json:"revoked_at"`
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
Fields []domain.ContactField `json:"fields,omitempty"`
}
func (effects consentRevocationEffects) appendRevocationIntent(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
events, err := newConsentRevocationEvents(revocation, records)
if err != nil {
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - build events: %w", err)
}
if err := outboxWriter(effects).Append(ctx, events...); err != nil {
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - append events: %w", err)
}
return nil
}
func newConsentRevocationEvents(revocation domain.ConsentRevocation, records []domain.ConsentRecord) ([]domain.DomainEvent, error) {
if revocation.IsZero() || len(records) == 0 {
return nil, fmt.Errorf("newConsentRevocationEvents - revocation and records are required: %w", domain.ErrInvalidConsent)
}
revocationID, err := uuid.NewV7()
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - generate revocation ID: %w", err)
}
events := make([]domain.DomainEvent, 0, len(records))
for _, record := range records {
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
return nil, fmt.Errorf("newConsentRevocationEvents - record scope does not match revocation: %w", domain.ErrInvalidConsent)
}
payload := consentRevocationPayload{
RevocationID: revocationID, RecordID: record.ID(), SubjectID: revocation.SubjectID(),
Purpose: revocation.Purpose(), Source: revocation.Source(), RevokedAt: revocation.RevokedAt(),
}
if revocation.Purpose().OrganizationScoped() {
organizationID := record.OrganizationID()
payload.OrganizationID = &organizationID
payload.Fields = record.Fields().Fields()
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - marshal payload: %w", err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: "consent.revoked", SchemaVersion: 1, AggregateType: "consent_record",
AggregateID: record.ID(), AggregateVersion: 2, Payload: body,
})
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - build event: %w", err)
}
events = append(events, event)
}
return events, nil
}
@@ -0,0 +1,91 @@
package postgres
import (
"encoding/json"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestConsentRevocationEventsStayBoundedForLargeContactHistory(t *testing.T) {
const historySize = 500
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
organization := uuid.New()
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now,
})
if err != nil {
t.Fatal(err)
}
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
fieldCodes := make([]string, 0, len(fields.Fields()))
for _, field := range fields.Fields() {
fieldCodes = append(fieldCodes, string(field))
}
hash := domain.HashConsentText("c4 text with the stored organization snapshot")
records := make([]domain.ConsentRecord, 0, historySize)
legacyFacts := make([]uuid.UUID, 0, historySize)
for index := 0; index < historySize; index++ {
id := uuid.New()
legacyFacts = append(legacyFacts, id)
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: id, SubjectID: subject, Purpose: string(domain.ConsentPurposeContactDisclosure),
TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
State: string(domain.ConsentStateActive), GrantedAt: now.Add(-time.Duration(index+1) * time.Minute),
OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", FieldSet: fieldCodes,
InvitationID: uuid.New(), InvitationTermsVersion: 1,
})
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
records = append(records, record)
}
legacyPayload, err := json.Marshal(map[string]any{"records": legacyFacts})
if err != nil {
t.Fatal(err)
}
if len(legacyPayload) <= domain.MaxDomainEventPayloadBytes {
t.Fatalf("legacy aggregate fixture has %d bytes; expected it to exceed %d", len(legacyPayload), domain.MaxDomainEventPayloadBytes)
}
events, err := newConsentRevocationEvents(revocation, records)
if err != nil {
t.Fatalf("newConsentRevocationEvents() error = %v", err)
}
if len(events) != historySize {
t.Fatalf("event count = %d, want one for every revoked record (%d)", len(events), historySize)
}
seen := make(map[uuid.UUID]bool, historySize)
for _, event := range events {
if event.AggregateType() != "consent_record" || event.AggregateVersion() != 2 || event.EventType() != "consent.revoked" {
t.Fatalf("event identity = %s/%s/%d, want one revoked record version", event.EventType(), event.AggregateType(), event.AggregateVersion())
}
if len(event.Payload()) > domain.MaxDomainEventPayloadBytes {
t.Fatalf("event payload has %d bytes, above the limit", len(event.Payload()))
}
var payload struct {
RecordID uuid.UUID `json:"record_id"`
SubjectID uuid.UUID `json:"subject_id"`
Purpose domain.ConsentPurpose `json:"purpose"`
OrganizationID uuid.UUID `json:"organization_id"`
Fields []domain.ContactField `json:"fields"`
}
if err := json.Unmarshal(event.Payload(), &payload); err != nil {
t.Fatalf("decode event payload: %v", err)
}
if event.AggregateID() != payload.RecordID || payload.RecordID == uuid.Nil || seen[payload.RecordID] ||
payload.SubjectID != subject || payload.Purpose != domain.ConsentPurposeContactDisclosure ||
payload.OrganizationID != organization || len(payload.Fields) != 1 || payload.Fields[0] != domain.ContactFieldPhone {
t.Fatalf("event payload lost or changed a stored revocation fact: %+v", payload)
}
seen[payload.RecordID] = true
}
}
@@ -22,11 +22,12 @@ import (
// never by text. The duplicate grants of the ledger are no errors: the
// inserts use ON CONFLICT DO NOTHING.
var consentConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound,
{foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch,
{checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished,
{checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch,
{foreignKeyViolationCode, "account_deletion_requests_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound,
{foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch,
{checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished,
{checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch,
// The revoke queries clamp the time to the grant, so this stays a
// backstop for a revocation written around them.
{checkViolationCode, "consent_records_revocation_stamp"}: domain.ErrInvalidConsent,
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -59,6 +60,8 @@ type organizationRepository struct {
var _ outbound.OrganizationRepository = organizationRepository{}
const maxOrganizationCreationSnapshotBytes = 65536
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
@@ -100,6 +103,158 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
return nil
}
func (repository organizationRepository) SaveCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.OrganizationCreationResult,
) error {
const location = "organizationRepository.SaveCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) || result.Organization.IsZero() || result.Owner.IsZero() ||
result.Owner.OrganizationID() != result.Organization.ID() || result.Owner.Role() != domain.OrganizationRoleOwner ||
!result.Owner.GrantsAccess() {
return fmt.Errorf("%s - scope and active owner result must be set: %w", location, domain.ErrInvalidOrganization)
}
snapshot := creationSnapshotFromDomain(result)
encoded, err := json.Marshal(snapshot)
if err != nil {
return fmt.Errorf("%s - encode domain snapshot", location)
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
return fmt.Errorf("%s - domain snapshot exceeds its storage bound: %w", location, domain.ErrInvalidOrganization)
}
if err := repository.queries.SaveOrganizationCreationResult(ctx, sqlc.SaveOrganizationCreationResultParams{
ScopeHash: scope[:],
Snapshot: encoded,
}); err != nil {
return fmt.Errorf("%s - store domain snapshot: %w", location, mapOrganizationError(err))
}
return nil
}
func (repository organizationRepository) GetCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.OrganizationCreationResult, error) {
const location = "organizationRepository.GetCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - scope must be set: %w", location, domain.ErrInvalidOrganization)
}
encoded, err := repository.queries.GetOrganizationCreationResult(ctx, scope[:])
if err != nil {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - read domain snapshot: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationCreationResultNotFound))
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot exceeds its bound", location)
}
var snapshot organizationCreationSnapshot
if err := json.Unmarshal(encoded, &snapshot); err != nil {
// The snapshot contains company profile data and representative names.
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot is invalid", location)
}
result, err := snapshot.domainResult()
if err != nil {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - restore domain snapshot: %w", location, err)
}
return result, nil
}
type organizationCreationSnapshot struct {
Organization organizationCreationOrganizationSnapshot `json:"organization"`
Owner organizationCreationMembershipSnapshot `json:"owner"`
}
type organizationCreationOrganizationSnapshot struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Sphere string `json:"sphere"`
Website string `json:"website"`
Email string `json:"email"`
Phone string `json:"phone"`
Telegram string `json:"telegram"`
Representatives []organizationCreationRepresentativeSnapshot `json:"representatives"`
VerificationLevel string `json:"verification_level"`
VerificationBasis string `json:"verification_basis"`
VerificationChangedAt time.Time `json:"verification_changed_at"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type organizationCreationRepresentativeSnapshot struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
type organizationCreationMembershipSnapshot struct {
ID uuid.UUID `json:"id"`
OrganizationID uuid.UUID `json:"organization_id"`
UserID uuid.UUID `json:"user_id"`
Role string `json:"role"`
State string `json:"state"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func creationSnapshotFromDomain(result outbound.OrganizationCreationResult) organizationCreationSnapshot {
organization := result.Organization
profile := organization.Profile()
contacts := profile.Contacts()
representatives := profile.Representatives()
snapshotRepresentatives := make([]organizationCreationRepresentativeSnapshot, 0, len(representatives))
for _, representative := range representatives {
snapshotRepresentatives = append(snapshotRepresentatives, organizationCreationRepresentativeSnapshot{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
verification := organization.Verification()
owner := result.Owner
return organizationCreationSnapshot{
Organization: organizationCreationOrganizationSnapshot{
ID: organization.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(),
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
Representatives: snapshotRepresentatives, VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(),
Version: organization.Version(), CreatedAt: organization.CreatedAt(), UpdatedAt: organization.UpdatedAt(),
},
Owner: organizationCreationMembershipSnapshot{
ID: owner.ID(), OrganizationID: owner.OrganizationID(), UserID: owner.UserID(), Role: string(owner.Role()),
State: string(owner.State()), CreatedAt: owner.CreatedAt(), UpdatedAt: owner.UpdatedAt(),
},
}
}
func (snapshot organizationCreationSnapshot) domainResult() (outbound.OrganizationCreationResult, error) {
stored := snapshot.Organization
representatives := make([]domain.StoredRepresentative, 0, len(stored.Representatives))
for _, representative := range stored.Representatives {
representatives = append(representatives, domain.StoredRepresentative{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: stored.ID, Name: stored.Name, Description: stored.Description, Sphere: stored.Sphere,
Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram,
Representatives: representatives, VerificationLevel: stored.VerificationLevel, VerificationBasis: stored.VerificationBasis,
VerificationChangedAt: stored.VerificationChangedAt, Version: stored.Version, CreatedAt: stored.CreatedAt, UpdatedAt: stored.UpdatedAt,
})
if err != nil {
return outbound.OrganizationCreationResult{}, err
}
owner := snapshot.Owner
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: owner.ID, OrganizationID: owner.OrganizationID, UserID: owner.UserID,
Role: owner.Role, State: owner.State, CreatedAt: owner.CreatedAt, UpdatedAt: owner.UpdatedAt,
})
if err != nil {
return outbound.OrganizationCreationResult{}, err
}
if membership.OrganizationID() != organization.ID() || membership.Role() != domain.OrganizationRoleOwner || !membership.GrantsAccess() {
return outbound.OrganizationCreationResult{}, domain.ErrInvalidMembership
}
return outbound.OrganizationCreationResult{Organization: organization, Owner: membership}, nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
@@ -2,9 +2,11 @@ package postgres
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
@@ -81,3 +83,50 @@ func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
func TestOrganizationCreationSnapshotRoundTripsDomainResult(t *testing.T) {
at := time.Date(2026, 8, 15, 10, 30, 0, 123456789, time.UTC)
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
Name: "ООО Пример", Description: "Описание", Sphere: "Платежи",
Contacts: domain.OrganizationContactsInput{
Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example",
},
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}},
})
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
company, err := domain.NewOrganization(profile, at)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
owner, err := domain.NewOwnerMembership(company.ID(), uuid.New(), at)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
result := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
snapshot := creationSnapshotFromDomain(result)
encoded, err := json.Marshal(snapshot)
if err != nil {
t.Fatalf("Marshal(snapshot) error = %v", err)
}
var decoded organizationCreationSnapshot
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("Unmarshal(snapshot) error = %v", err)
}
got, err := decoded.domainResult()
if err != nil {
t.Fatalf("domainResult() error = %v", err)
}
if got.Organization.ID() != company.ID() || got.Organization.Version() != company.Version() ||
!got.Organization.Profile().Equal(company.Profile()) ||
got.Organization.Verification().Level() != domain.OrganizationVerificationE0 ||
got.Organization.Verification().Basis() != domain.OrganizationBasisConfirmedEmail ||
!got.Organization.CreatedAt().Equal(at) || got.Owner.ID() != owner.ID() || got.Owner.UserID() != owner.UserID() ||
got.Owner.OrganizationID() != company.ID() || got.Owner.Role() != domain.OrganizationRoleOwner || !got.Owner.GrantsAccess() {
t.Fatal("creation snapshot did not preserve the original organization and owner result")
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
t.Fatalf("snapshot size = %d, want at most %d bytes", len(encoded), maxOrganizationCreationSnapshotBytes)
}
}
@@ -11,6 +11,82 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const createAccountDeletionRequest = `-- name: CreateAccountDeletionRequest :one
INSERT INTO account_deletion_requests (
id,
subject_id,
status,
requested_at
) VALUES (
$1,
$2,
'requested',
$3
)
ON CONFLICT (subject_id)
WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing')
DO NOTHING
RETURNING id, subject_id, status, requested_at
`
type CreateAccountDeletionRequestParams struct {
ID pgtype.UUID
SubjectID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
type CreateAccountDeletionRequestRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
}
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
func (q *Queries) CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error) {
row := q.db.QueryRow(ctx, createAccountDeletionRequest, arg.ID, arg.SubjectID, arg.RequestedAt)
var i CreateAccountDeletionRequestRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Status,
&i.RequestedAt,
)
return i, err
}
const getActiveAccountDeletionRequest = `-- name: GetActiveAccountDeletionRequest :one
SELECT id, subject_id, status, requested_at
FROM account_deletion_requests
WHERE subject_id = $1
AND status IN ('requested', 'processing')
ORDER BY requested_at, id
LIMIT 1
`
type GetActiveAccountDeletionRequestRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
}
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
func (q *Queries) GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error) {
row := q.db.QueryRow(ctx, getActiveAccountDeletionRequest, subjectID)
var i GetActiveAccountDeletionRequestRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Status,
&i.RequestedAt,
)
return i, err
}
const getConsentText = `-- name: GetConsentText :one
SELECT
purpose,
@@ -8,6 +8,14 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type AccountDeletionRequest struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
CompletedAt pgtype.Timestamptz
}
type AssessmentCategoryOpening struct {
ID pgtype.UUID
Category string
@@ -315,6 +323,11 @@ type Organization struct {
UpdatedAt pgtype.Timestamptz
}
type OrganizationCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
@@ -57,6 +57,21 @@ func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (M
return i, err
}
const getOrganizationCreationResult = `-- name: GetOrganizationCreationResult :one
SELECT snapshot
FROM organization_creation_results
WHERE scope_hash = $1
`
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
func (q *Queries) GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) {
row := q.db.QueryRow(ctx, getOrganizationCreationResult, scopeHash)
var snapshot []byte
err := row.Scan(&snapshot)
return snapshot, err
}
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
SELECT
organization.id,
@@ -390,6 +405,27 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
return items, nil
}
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES ($1, $2)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveOrganizationCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
// 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
// same transaction as the new organization.
func (q *Queries) SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error {
_, err := q.db.Exec(ctx, saveOrganizationCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
@@ -421,6 +421,38 @@ func (q *Queries) ListCandidatePrivacyEvents(ctx context.Context, arg ListCandid
return items, nil
}
const lockCandidatePublicationForConsentRevocation = `-- name: LockCandidatePublicationForConsentRevocation :one
SELECT greatest(candidate_publications.published_at, consent_records.revoked_at)::timestamptz AS closed_at
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND consent_records.id = ANY($2::uuid [])
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NOT NULL
FOR UPDATE OF candidate_publications
`
type LockCandidatePublicationForConsentRevocationParams struct {
UserID pgtype.UUID
ConsentRecordIds []pgtype.UUID
}
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
// keeps the consent-revoked reason after later grants. The returned time is
// the effective close time used by the privacy history event.
func (q *Queries) LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, lockCandidatePublicationForConsentRevocation, arg.UserID, arg.ConsentRecordIds)
var closed_at pgtype.Timestamptz
err := row.Scan(&closed_at)
return closed_at, err
}
const lockCurrentC2Record = `-- name: LockCurrentC2Record :one
SELECT id
FROM consent_records
@@ -107,6 +107,10 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// Lifts one hiding. No row returns when the organization was not hidden, so
// the caller writes the history event only for a real deletion and answers
// 204 either way.
@@ -156,6 +160,9 @@ type Querier interface {
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
@@ -207,6 +214,9 @@ type Querier interface {
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
@@ -377,6 +387,12 @@ type Querier interface {
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
// keeps the consent-revoked reason after later grants. The returned time is
// the effective close time used by the privacy history event.
LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error)
// Locks the delivery row of the lease holder until the transaction ends, so
// every path that settles a send takes the delivery lock before the quota
// rows, the same order as the claim. No row means that owner no longer holds
@@ -542,6 +558,11 @@ type Querier interface {
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, 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
// same transaction as the new organization.
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the