Files

75 lines
2.5 KiB
Go

package postgres
import (
"context"
"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/port/outbound"
)
var (
_ outbound.AssessmentSignalNoticeRepositories = (*UnitOfWork)(nil)
_ outbound.AssessmentSignalNoticeRepository = assessmentSignalNoticeRepository{}
)
func (unit *UnitOfWork) AssessmentSignalNotices() outbound.AssessmentSignalNoticeRepository {
return assessmentSignalNoticeRepository{queries: unit.queries}
}
type assessmentSignalNoticeRepository struct {
queries *sqlc.Queries
}
func (repository assessmentSignalNoticeRepository) Get(
ctx context.Context,
userID uuid.UUID,
version int32,
) (time.Time, error) {
const location = "assessmentSignalNoticeRepository.Get"
if userID == uuid.Nil || version < 1 {
return time.Time{}, fmt.Errorf("%s - user and notice version are required", location)
}
stored, err := repository.queries.GetAssessmentSignalNoticeAcknowledgement(ctx, sqlc.GetAssessmentSignalNoticeAcknowledgementParams{
UserID: pgUUID(userID), NoticeVersion: version,
})
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, outbound.ErrAssessmentSignalNoticeNotAcknowledged)
}
if err != nil {
return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, mapAssessmentError(err))
}
return acknowledgementTime(location, stored)
}
func (repository assessmentSignalNoticeRepository) Acknowledge(
ctx context.Context,
userID uuid.UUID,
version int32,
at time.Time,
) (time.Time, error) {
const location = "assessmentSignalNoticeRepository.Acknowledge"
if userID == uuid.Nil || version < 1 || at.IsZero() {
return time.Time{}, fmt.Errorf("%s - user, notice version, and time are required", location)
}
if err := repository.queries.InsertAssessmentSignalNoticeAcknowledgement(ctx, sqlc.InsertAssessmentSignalNoticeAcknowledgementParams{
UserID: pgUUID(userID), NoticeVersion: version, AcknowledgedAt: pgTime(at),
}); err != nil {
return time.Time{}, fmt.Errorf("%s - insert acknowledgement: %w", location, mapAssessmentError(err))
}
return repository.Get(ctx, userID, version)
}
func acknowledgementTime(location string, stored pgtype.Timestamptz) (time.Time, error) {
if !stored.Valid || stored.Time.IsZero() {
return time.Time{}, fmt.Errorf("%s - stored acknowledgement time is missing", location)
}
return stored.Time.UTC(), nil
}