619 lines
25 KiB
Go
619 lines
25 KiB
Go
package postgres
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"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"
|
|
)
|
|
|
|
const maxSupportCaseSnapshotBytes = 1 << 20
|
|
|
|
var supportCaseConstraintErrors = map[constraintViolation]error{
|
|
{foreignKeyViolationCode, "support_cases_owner_id_fkey"}: outbound.ErrUserNotFound,
|
|
{foreignKeyViolationCode, "support_case_create_outcomes_scope_hash_fkey"}: outbound.ErrIdempotencyRecordNotFound,
|
|
}
|
|
|
|
var (
|
|
_ outbound.SupportCaseRepository = supportCaseRepository{}
|
|
_ outbound.SupportCaseCreateOutcomeRepository = supportCaseRepository{}
|
|
_ outbound.SupportCaseRequestLimitRepository = supportCaseRepository{}
|
|
_ outbound.SupportCaseRepositories = (*UnitOfWork)(nil)
|
|
)
|
|
|
|
func (unit *UnitOfWork) SupportCases() outbound.SupportCaseRepository {
|
|
return supportCaseRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) SupportCaseCreateOutcomes() outbound.SupportCaseCreateOutcomeRepository {
|
|
return supportCaseRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) SupportCaseRequestLimits() outbound.SupportCaseRequestLimitRepository {
|
|
return supportCaseRepository{queries: unit.queries}
|
|
}
|
|
|
|
type supportCaseRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func (repository supportCaseRepository) NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) {
|
|
const location = "supportCaseRepository.NextNumber"
|
|
if createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 {
|
|
return "", fmt.Errorf("%s - creation time is invalid: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
value, err := repository.queries.NextSupportCaseNumber(ctx, fmt.Sprintf("%04d", createdAt.UTC().Year()))
|
|
if err != nil {
|
|
return "", fmt.Errorf("%s - allocate number: %w", location, mapSupportCaseError(err))
|
|
}
|
|
var number string
|
|
switch stored := value.(type) {
|
|
case string:
|
|
number = stored
|
|
case []byte:
|
|
number = string(stored)
|
|
default:
|
|
return "", fmt.Errorf("%s - database returned an invalid number type", location)
|
|
}
|
|
parsed, err := domain.ParseSupportCaseNumber(number)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%s - database returned an invalid number", location)
|
|
}
|
|
return parsed, nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) Create(ctx context.Context, supportCase domain.SupportCase) error {
|
|
const location = "supportCaseRepository.Create"
|
|
if supportCase.IsZero() {
|
|
return fmt.Errorf("%s - case is not initialized: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
snapshot := supportCase.Snapshot()
|
|
validated, err := domain.RestoreSupportCase(snapshot)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate case: %w", location, err)
|
|
}
|
|
snapshot = validated.Snapshot()
|
|
row := supportCaseInsertParams(snapshot)
|
|
inserted, err := repository.queries.InsertSupportCase(ctx, row)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - insert case: %w", location, mapSupportCaseError(err))
|
|
}
|
|
if inserted != 1 {
|
|
return fmt.Errorf("%s - unique business rule rejected the case: %w", location, outbound.ErrSupportCaseConflict)
|
|
}
|
|
for _, event := range snapshot.History {
|
|
if err := repository.queries.InsertSupportCaseEvent(ctx, supportCaseEventParams(snapshot.ID.UUID(), event)); err != nil {
|
|
return fmt.Errorf("%s - insert public event: %w", location, mapSupportCaseError(err))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) {
|
|
const location = "supportCaseRepository.GetOwned"
|
|
if ownerID == uuid.Nil || caseID.IsZero() {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - scope identifiers are invalid: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
row, err := repository.queries.ReadOwnedSupportCase(ctx, sqlc.ReadOwnedSupportCaseParams{
|
|
CaseID: pgUUID(caseID.UUID()), OwnerID: pgUUID(ownerID),
|
|
})
|
|
if err != nil {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - read owner-scoped case: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseNotFound))
|
|
}
|
|
events, err := repository.queries.ReadSupportCaseEvents(ctx, pgUUID(caseID.UUID()))
|
|
if err != nil {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - read public history: %w", location, mapSupportCaseError(err))
|
|
}
|
|
snapshot, err := supportCaseSnapshotFromRow(row, events)
|
|
if err != nil {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - restore stored case: %w", location, err)
|
|
}
|
|
if snapshot.OwnerID != ownerID || snapshot.ID != caseID {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - stored case scope does not match query", location)
|
|
}
|
|
supportCase, err := domain.RestoreSupportCase(snapshot)
|
|
if err != nil {
|
|
return domain.SupportCase{}, fmt.Errorf("%s - validate stored case: %w", location, err)
|
|
}
|
|
return supportCase, nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) ListOwned(ctx context.Context, query outbound.SupportCaseListQuery) (outbound.SupportCaseListPage, error) {
|
|
const location = "supportCaseRepository.ListOwned"
|
|
if query.OwnerID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxSupportCasePageSize {
|
|
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - owner and page limit are invalid: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
params := sqlc.ListOwnedSupportCasesParams{OwnerID: pgUUID(query.OwnerID), RowLimit: query.Limit + 1}
|
|
if query.After != nil {
|
|
if query.After.ID.IsZero() || !validSupportCasePositionTime(query.After.CreatedAt) {
|
|
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - cursor position is invalid: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
params.AfterCreatedAt = pgTime(query.After.CreatedAt.UTC())
|
|
params.AfterID = pgUUID(query.After.ID.UUID())
|
|
}
|
|
rows, err := repository.queries.ListOwnedSupportCases(ctx, params)
|
|
if err != nil {
|
|
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - select owner-scoped summaries: %w", location, mapSupportCaseError(err))
|
|
}
|
|
page := outbound.SupportCaseListPage{HasMore: len(rows) > int(query.Limit)}
|
|
if page.HasMore {
|
|
rows = rows[:query.Limit]
|
|
}
|
|
page.Items = make([]domain.SupportCaseSummary, 0, len(rows))
|
|
for _, row := range rows {
|
|
summary, err := supportCaseSummaryFromRow(row)
|
|
if err != nil {
|
|
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - restore stored summary: %w", location, err)
|
|
}
|
|
page.Items = append(page.Items, summary)
|
|
}
|
|
return page, nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) DeleteCreateOutcome(ctx context.Context, scope [outbound.IdempotencyDigestSize]byte) error {
|
|
const location = "supportCaseRepository.DeleteCreateOutcome"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return fmt.Errorf("%s - idempotency scope must be set", location)
|
|
}
|
|
if err := repository.queries.DeleteSupportCaseCreateOutcome(ctx, scope[:]); err != nil {
|
|
return fmt.Errorf("%s - delete expired outcome: %w", location, mapSupportCaseError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) SaveCreateOutcome(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
outcome domain.SupportCaseCreateOutcome,
|
|
createdAt time.Time,
|
|
) error {
|
|
const location = "supportCaseRepository.SaveCreateOutcome"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) || !validSupportCasePositionTime(createdAt) {
|
|
return fmt.Errorf("%s - scope and creation time must be valid", location)
|
|
}
|
|
validated, err := domain.RestoreSupportCaseCreateOutcome(outcome.Snapshot())
|
|
if err != nil {
|
|
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
|
}
|
|
snapshot := validated.Snapshot()
|
|
encoded := []byte(`{}`)
|
|
var targetWasLate bool
|
|
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
|
|
encoded, err = json.Marshal(snapshot.Case)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - encode outcome snapshot", location)
|
|
}
|
|
if len(encoded) > maxSupportCaseSnapshotBytes {
|
|
return fmt.Errorf("%s - outcome snapshot exceeds its storage bound: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
targetWasLate = snapshot.TargetWasLate
|
|
}
|
|
if err := repository.queries.InsertSupportCaseCreateOutcome(ctx, sqlc.InsertSupportCaseCreateOutcomeParams{
|
|
ScopeHash: scope[:], OutcomeKind: string(snapshot.Kind), CaseSnapshot: encoded,
|
|
TargetWasLate: targetWasLate, CreatedAt: pgTime(createdAt.UTC().Truncate(time.Microsecond)),
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - insert immutable outcome: %w", location, mapSupportCaseError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) GetCreateOutcome(
|
|
ctx context.Context,
|
|
scope [outbound.IdempotencyDigestSize]byte,
|
|
) (domain.SupportCaseCreateOutcome, error) {
|
|
const location = "supportCaseRepository.GetCreateOutcome"
|
|
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - idempotency scope must be set", location)
|
|
}
|
|
row, err := repository.queries.ReadSupportCaseCreateOutcome(ctx, scope[:])
|
|
if err != nil {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - read immutable outcome: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseCreateOutcomeNotFound))
|
|
}
|
|
snapshot := domain.SupportCaseCreateOutcomeSnapshot{Kind: domain.SupportCaseCreateOutcomeKind(row.OutcomeKind)}
|
|
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
|
|
encoded, ok := supportCaseJSONBytes(row.CaseSnapshot)
|
|
if !ok || len(encoded) == 0 || len(encoded) > maxSupportCaseSnapshotBytes || !row.TargetWasLate.Valid {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored created outcome is invalid", location)
|
|
}
|
|
var stored domain.SupportCaseSnapshot
|
|
if err := decodeSupportCaseJSON(encoded, &stored); err != nil {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored case snapshot is invalid", location)
|
|
}
|
|
snapshot.Case = &stored
|
|
snapshot.TargetWasLate = row.TargetWasLate.Bool
|
|
} else if row.TargetWasLate.Valid {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored failure outcome has a late flag", location)
|
|
}
|
|
outcome, err := domain.RestoreSupportCaseCreateOutcome(snapshot)
|
|
if err != nil {
|
|
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
|
}
|
|
return outcome, nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) Consume(
|
|
ctx context.Context,
|
|
ownerID uuid.UUID,
|
|
at time.Time,
|
|
maxRequests int32,
|
|
window time.Duration,
|
|
) (outbound.SupportCaseRequestLimitResult, error) {
|
|
const location = "supportCaseRepository.Consume"
|
|
if ownerID == uuid.Nil || !validSupportCasePositionTime(at) || maxRequests < 1 || window < time.Second ||
|
|
window > domain.MaxSupportRequestWindow || window%time.Second != 0 {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - request budget parameters are invalid: %w", location, domain.ErrInvalidSupportCase)
|
|
}
|
|
at = at.UTC().Truncate(time.Microsecond)
|
|
if _, err := repository.queries.PruneSupportCaseRequestEvents(ctx, sqlc.PruneSupportCaseRequestEventsParams{
|
|
OwnerID: pgUUID(ownerID), At: pgTime(at),
|
|
}); err != nil {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - prune request history: %w", location, mapSupportCaseError(err))
|
|
}
|
|
windowStart := at.Add(-window)
|
|
count, err := repository.queries.CountSupportCaseRequestEvents(ctx, sqlc.CountSupportCaseRequestEventsParams{
|
|
OwnerID: pgUUID(ownerID), WindowStart: pgTime(windowStart), At: pgTime(at),
|
|
})
|
|
if err != nil {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - count request history: %w", location, mapSupportCaseError(err))
|
|
}
|
|
if count.EventCount >= int64(maxRequests) {
|
|
first, ok := supportCaseFirstEventTime(count.FirstInWindow)
|
|
if !ok {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - oldest qualifying event is missing", location)
|
|
}
|
|
retryAfter := first.Add(window).Sub(at)
|
|
if retryAfter <= 0 {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - retry interval is invalid", location)
|
|
}
|
|
return outbound.SupportCaseRequestLimitResult{Allowed: false, RetryAfter: retryAfter}, nil
|
|
}
|
|
if err := repository.queries.InsertSupportCaseRequestEvent(ctx, sqlc.InsertSupportCaseRequestEventParams{
|
|
OwnerID: pgUUID(ownerID), RequestedAt: pgTime(at),
|
|
}); err != nil {
|
|
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - record request: %w", location, mapSupportCaseError(err))
|
|
}
|
|
return outbound.SupportCaseRequestLimitResult{Allowed: true}, nil
|
|
}
|
|
|
|
func (repository supportCaseRepository) LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) {
|
|
const location = "supportCaseRepository.LockOwner"
|
|
if ownerID == uuid.Nil {
|
|
return time.Time{}, fmt.Errorf("%s - owner ID must be set", location)
|
|
}
|
|
if err := repository.queries.LockSupportCaseRequestBudget(ctx, pgUUID(ownerID)); err != nil {
|
|
return time.Time{}, fmt.Errorf("%s - take transaction lock: %w", location, mapSupportCaseError(err))
|
|
}
|
|
latest, err := repository.queries.LatestSupportCaseRequestEvent(ctx, pgUUID(ownerID))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return time.Time{}, nil
|
|
}
|
|
if err != nil {
|
|
return time.Time{}, fmt.Errorf("%s - read latest request timestamp: %w", location, mapSupportCaseError(err))
|
|
}
|
|
if !validSupportCasePositionTime(latest.Time) {
|
|
return time.Time{}, fmt.Errorf("%s - stored request timestamp is invalid", location)
|
|
}
|
|
return latest.Time.UTC().Truncate(time.Microsecond), nil
|
|
}
|
|
|
|
func supportCaseInsertParams(snapshot domain.SupportCaseSnapshot) sqlc.InsertSupportCaseParams {
|
|
return sqlc.InsertSupportCaseParams{
|
|
ID: pgUUID(snapshot.ID.UUID()), CaseNumber: snapshot.Number.String(), OwnerID: pgUUID(snapshot.OwnerID),
|
|
CaseType: string(snapshot.Type), Status: string(snapshot.Status), Description: snapshot.Description,
|
|
ObjectType: optionalSupportText(snapshot.Object, func(value *domain.SupportCaseReference) string { return string(value.Type) }),
|
|
ObjectID: optionalSupportUUID(snapshot.Object),
|
|
AssessmentSpecialization: optionalSupportAssessment(snapshot.AssessmentTarget, true),
|
|
AssessmentGrade: optionalSupportAssessment(snapshot.AssessmentTarget, false),
|
|
ComplaintReason: optionalSupportComplaint(snapshot.ComplaintReason), RubricVersion: optionalSupportInt32(snapshot.RubricVersion),
|
|
RubricOpeningID: optionalSupportUUIDPointer(snapshot.RubricOpeningID),
|
|
RubricPolicyVersionID: optionalSupportPolicyID(snapshot.RubricPolicyID),
|
|
TargetBusinessDays: int32(snapshot.ResponseTarget.BusinessDays), TargetDueAt: pgTime(snapshot.ResponseTarget.DueAt),
|
|
TargetAnsweredAt: pgOptionalTime(snapshot.ResponseTarget.AnsweredAt), TargetPolicyVersion: snapshot.ResponseTarget.PolicyVersion,
|
|
TargetCalendarVersion: snapshot.ResponseTarget.CalendarVersion,
|
|
DecisionOutcome: optionalSupportDecision(snapshot.Decision, true), DecisionReason: optionalSupportDecision(snapshot.Decision, false),
|
|
DecisionAt: optionalSupportDecisionTime(snapshot.Decision), CreatedAt: pgTime(snapshot.CreatedAt), UpdatedAt: pgTime(snapshot.UpdatedAt),
|
|
}
|
|
}
|
|
|
|
func supportCaseEventParams(caseID uuid.UUID, event domain.SupportCaseEventSnapshot) sqlc.InsertSupportCaseEventParams {
|
|
return sqlc.InsertSupportCaseEventParams{
|
|
CaseID: pgUUID(caseID), Sequence: event.Sequence, EventKind: string(event.Kind), ActorKind: string(event.Actor),
|
|
OccurredAt: pgTime(event.OccurredAt), Status: optionalSupportEventStatus(event.Status), Message: optionalSupportEventMessage(event.Message),
|
|
}
|
|
}
|
|
|
|
func supportCaseSnapshotFromRow(row sqlc.SupportCase, events []sqlc.ReadSupportCaseEventsRow) (domain.SupportCaseSnapshot, error) {
|
|
const location = "supportCaseSnapshotFromRow"
|
|
if !row.ID.Valid || !row.OwnerID.Valid || !row.TargetDueAt.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
|
|
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - required stored fields are missing", location)
|
|
}
|
|
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
|
|
if err != nil {
|
|
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - case number is invalid", location)
|
|
}
|
|
snapshot := domain.SupportCaseSnapshot{
|
|
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, OwnerID: uuid.UUID(row.OwnerID.Bytes),
|
|
Type: domain.SupportCaseType(row.CaseType), Status: domain.SupportCaseStatus(row.Status), Description: row.Description,
|
|
Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
|
|
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
|
|
ComplaintReason: optionalSupportCaseComplaint(row.ComplaintReason), RubricVersion: optionalSupportCaseInt4(row.RubricVersion),
|
|
RubricOpeningID: optionalSupportCaseUUID(row.RubricOpeningID),
|
|
RubricPolicyID: optionalSupportCasePolicyID(row.RubricPolicyVersionID),
|
|
ResponseTarget: domain.SupportResponseTargetSnapshot{
|
|
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
|
|
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
|
|
CalendarVersion: row.TargetCalendarVersion,
|
|
},
|
|
Decision: supportCaseDecisionFromColumns(row.DecisionOutcome, row.DecisionReason, row.DecisionAt),
|
|
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
|
History: make([]domain.SupportCaseEventSnapshot, 0, len(events)),
|
|
}
|
|
for _, stored := range events {
|
|
if !stored.OccurredAt.Valid {
|
|
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - stored event timestamp is missing", location)
|
|
}
|
|
snapshot.History = append(snapshot.History, domain.SupportCaseEventSnapshot{
|
|
Sequence: stored.Sequence, Kind: domain.SupportCaseEventKind(stored.EventKind), Actor: domain.SupportCaseActorKind(stored.ActorKind),
|
|
OccurredAt: stored.OccurredAt.Time, Status: optionalSupportCaseStatus(stored.Status), Message: optionalSupportCaseText(stored.Message),
|
|
})
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func supportCaseSummaryFromRow(row sqlc.ListOwnedSupportCasesRow) (domain.SupportCaseSummary, error) {
|
|
const location = "supportCaseSummaryFromRow"
|
|
if !row.ID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || !row.TargetDueAt.Valid {
|
|
return domain.SupportCaseSummary{}, fmt.Errorf("%s - required stored fields are missing", location)
|
|
}
|
|
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
|
|
if err != nil {
|
|
return domain.SupportCaseSummary{}, fmt.Errorf("%s - case number is invalid", location)
|
|
}
|
|
summary := domain.SupportCaseSummary{
|
|
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, Type: domain.SupportCaseType(row.CaseType),
|
|
Status: domain.SupportCaseStatus(row.Status), Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
|
|
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
|
|
ResponseTarget: domain.SupportResponseTargetSnapshot{
|
|
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
|
|
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
|
|
CalendarVersion: row.TargetCalendarVersion,
|
|
},
|
|
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
|
}
|
|
if row.DecisionOutcome.Valid {
|
|
outcome := domain.SupportCaseDecisionOutcome(row.DecisionOutcome.String)
|
|
summary.DecisionOutcome = &outcome
|
|
}
|
|
return domain.RestoreSupportCaseSummary(summary)
|
|
}
|
|
|
|
func supportCaseReferenceFromColumns(objectType pgtype.Text, objectID pgtype.UUID) *domain.SupportCaseReference {
|
|
if !objectType.Valid && !objectID.Valid {
|
|
return nil
|
|
}
|
|
return &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(objectType.String), ID: uuid.UUID(objectID.Bytes)}
|
|
}
|
|
|
|
func supportCaseAssessmentFromColumns(specialization, grade pgtype.Text) *domain.SupportCaseAssessmentTarget {
|
|
if !specialization.Valid && !grade.Valid {
|
|
return nil
|
|
}
|
|
return &domain.SupportCaseAssessmentTarget{
|
|
Specialization: domain.SpecializationCode(specialization.String), Grade: domain.GradeCode(grade.String),
|
|
}
|
|
}
|
|
|
|
func supportCaseDecisionFromColumns(outcome, reason pgtype.Text, at pgtype.Timestamptz) *domain.SupportCaseDecisionSnapshot {
|
|
if !outcome.Valid && !reason.Valid && !at.Valid {
|
|
return nil
|
|
}
|
|
return &domain.SupportCaseDecisionSnapshot{
|
|
Outcome: domain.SupportCaseDecisionOutcome(outcome.String), Reason: reason.String, DecidedAt: at.Time,
|
|
}
|
|
}
|
|
|
|
func optionalSupportText[T any](value *T, selectValue func(*T) string) pgtype.Text {
|
|
if value == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
return pgText(selectValue(value))
|
|
}
|
|
|
|
func optionalSupportUUID(reference *domain.SupportCaseReference) pgtype.UUID {
|
|
if reference == nil {
|
|
return pgtype.UUID{}
|
|
}
|
|
return pgUUID(reference.ID)
|
|
}
|
|
|
|
func optionalSupportUUIDPointer(value *uuid.UUID) pgtype.UUID {
|
|
if value == nil {
|
|
return pgtype.UUID{}
|
|
}
|
|
return pgUUID(*value)
|
|
}
|
|
|
|
func optionalSupportPolicyID(value *domain.PolicyVersionID) pgtype.UUID {
|
|
if value == nil {
|
|
return pgtype.UUID{}
|
|
}
|
|
return pgUUID(value.UUID())
|
|
}
|
|
|
|
func optionalSupportAssessment(target *domain.SupportCaseAssessmentTarget, specialization bool) pgtype.Text {
|
|
if target == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
if specialization {
|
|
return pgText(string(target.Specialization))
|
|
}
|
|
return pgText(string(target.Grade))
|
|
}
|
|
|
|
func optionalSupportComplaint(reason *domain.SupportCaseComplaintReason) pgtype.Text {
|
|
if reason == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
return pgText(string(*reason))
|
|
}
|
|
|
|
func optionalSupportInt32(value *int32) pgtype.Int4 {
|
|
if value == nil {
|
|
return pgtype.Int4{}
|
|
}
|
|
return pgtype.Int4{Int32: *value, Valid: true}
|
|
}
|
|
|
|
func optionalSupportDecision(decision *domain.SupportCaseDecisionSnapshot, outcome bool) pgtype.Text {
|
|
if decision == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
if outcome {
|
|
return pgText(string(decision.Outcome))
|
|
}
|
|
return pgText(decision.Reason)
|
|
}
|
|
|
|
func optionalSupportDecisionTime(decision *domain.SupportCaseDecisionSnapshot) pgtype.Timestamptz {
|
|
if decision == nil {
|
|
return pgtype.Timestamptz{}
|
|
}
|
|
return pgTime(decision.DecidedAt)
|
|
}
|
|
|
|
func optionalSupportEventStatus(status *domain.SupportCaseStatus) pgtype.Text {
|
|
if status == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
return pgText(string(*status))
|
|
}
|
|
|
|
func optionalSupportEventMessage(message *string) pgtype.Text {
|
|
if message == nil {
|
|
return pgtype.Text{}
|
|
}
|
|
return pgText(*message)
|
|
}
|
|
|
|
func optionalSupportCaseComplaint(value pgtype.Text) *domain.SupportCaseComplaintReason {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := domain.SupportCaseComplaintReason(value.String)
|
|
return &result
|
|
}
|
|
|
|
func optionalSupportCaseInt4(value pgtype.Int4) *int32 {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
return &value.Int32
|
|
}
|
|
|
|
func optionalSupportCaseUUID(value pgtype.UUID) *uuid.UUID {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := uuid.UUID(value.Bytes)
|
|
return &result
|
|
}
|
|
|
|
func optionalSupportCasePolicyID(value pgtype.UUID) *domain.PolicyVersionID {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := domain.PolicyVersionID(value.Bytes)
|
|
return &result
|
|
}
|
|
|
|
func optionalSupportCaseStatus(value pgtype.Text) *domain.SupportCaseStatus {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := domain.SupportCaseStatus(value.String)
|
|
return &result
|
|
}
|
|
|
|
func optionalSupportCaseText(value pgtype.Text) *string {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := value.String
|
|
return &result
|
|
}
|
|
|
|
func supportCaseFirstEventTime(value any) (time.Time, bool) {
|
|
switch typed := value.(type) {
|
|
case time.Time:
|
|
return typed, !typed.IsZero()
|
|
case pgtype.Timestamptz:
|
|
return typed.Time, typed.Valid && !typed.Time.IsZero()
|
|
case *time.Time:
|
|
if typed != nil {
|
|
return *typed, !typed.IsZero()
|
|
}
|
|
case nil:
|
|
return time.Time{}, false
|
|
}
|
|
return time.Time{}, false
|
|
}
|
|
|
|
func supportCaseJSONBytes(value any) ([]byte, bool) {
|
|
switch typed := value.(type) {
|
|
case string:
|
|
return []byte(typed), true
|
|
case []byte:
|
|
return typed, true
|
|
default:
|
|
return nil, false
|
|
}
|
|
}
|
|
|
|
func decodeSupportCaseJSON(encoded []byte, destination any) error {
|
|
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
return err
|
|
}
|
|
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
|
return errors.New("stored support case snapshot contains trailing data")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validSupportCasePositionTime(value time.Time) bool {
|
|
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 &&
|
|
value.Nanosecond()%int(time.Microsecond) == 0
|
|
}
|
|
|
|
func mapSupportCaseNoRows(err, sentinel error) error {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return sentinel
|
|
}
|
|
return mapSupportCaseError(err)
|
|
}
|
|
|
|
func mapSupportCaseError(err error) error {
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) {
|
|
return sanitizeConnectError(err)
|
|
}
|
|
key := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
|
|
if sentinel, ok := supportCaseConstraintErrors[key]; ok {
|
|
return fmt.Errorf("postgres.mapSupportCaseError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
|
|
}
|
|
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
|
}
|