package postgres import ( "context" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgtype" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" ) // contactGrantClosure names the active grants that one change closes. The // caller runs it in the transaction of the change, so the grants and the change // commit or roll back together. type contactGrantClosure struct { candidateID uuid.UUID // organizationID limits the closure to one organization. Nil closes every // organization of the candidate. organizationID uuid.UUID // consentRecordIDs limits the closure to the grants that these C4 records // gave. Nil applies no record filter. consentRecordIDs []uuid.UUID reason domain.ContactRevocationReason at time.Time } // closeActiveContactGrants stamps the active grants of the closure with its // reason and time. A grant already closed keeps its first stamp, and the // revocation time is never earlier than the grant time, as the grant requires. func closeActiveContactGrants(ctx context.Context, queries *sqlc.Queries, closure contactGrantClosure) error { const location = "postgres.closeActiveContactGrants" if closure.candidateID == uuid.Nil || closure.at.IsZero() || closure.reason == "" { return fmt.Errorf("%s - candidate, time, and reason are required: %w", location, domain.ErrInvalidContactGrant) } params := sqlc.CloseActiveContactGrantsParams{ RevokedAt: pgTime(closure.at), RevocationReason: pgtype.Text{String: string(closure.reason), Valid: true}, CandidateID: pgUUID(closure.candidateID), } if closure.organizationID != uuid.Nil { params.OrganizationID = pgUUID(closure.organizationID) } if closure.consentRecordIDs != nil { params.ConsentRecordIds = make([]pgtype.UUID, 0, len(closure.consentRecordIDs)) for _, id := range closure.consentRecordIDs { params.ConsentRecordIds = append(params.ConsentRecordIds, pgUUID(id)) } } if _, err := queries.CloseActiveContactGrants(ctx, params); err != nil { return fmt.Errorf("%s - close active grants: %w", location, markTransactionConflict(sanitizeConnectError(err))) } return nil }