Files

1471 lines
57 KiB
Go

package domain
import (
"errors"
"fmt"
"log/slog"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
var ErrInvalidSupportCase = errors.New("invalid support case")
// SupportCaseFieldError identifies an invalid user-provided field without
// including the submitted value. It matches ErrInvalidSupportCase.
type SupportCaseFieldError struct {
Pointer string
Reason string
}
func (fieldError *SupportCaseFieldError) Error() string {
return fmt.Sprintf("support case field %s %s", fieldError.Pointer, fieldError.Reason)
}
func (*SupportCaseFieldError) Unwrap() error { return ErrInvalidSupportCase }
const (
maxSupportCaseDescriptionRunes = 4000
maxSupportCasePublicTextRunes = 4000
maxSupportCaseEvents = 200
redactedSupportCase = "[redacted support case]"
redactedSupportCaseEvent = "[redacted support case event]"
redactedSupportCaseDecision = "[redacted support case decision]"
)
var supportCaseNumberPattern = regexp.MustCompile(`^SC-([0-9]{4})-([0-9]{6,10})$`)
// SupportCaseID identifies a support case.
type SupportCaseID uuid.UUID
// NewSupportCaseID returns a time-ordered UUIDv7.
func NewSupportCaseID() (SupportCaseID, error) {
id, err := uuid.NewV7()
if err != nil {
return SupportCaseID{}, fmt.Errorf("domain.NewSupportCaseID - generate ID: %w", err)
}
return SupportCaseID(id), nil
}
func (id SupportCaseID) UUID() uuid.UUID { return uuid.UUID(id) }
func (id SupportCaseID) String() string { return uuid.UUID(id).String() }
func (id SupportCaseID) IsZero() bool { return uuid.UUID(id) == uuid.Nil }
// SupportCaseNumber is the immutable public number assigned by storage.
type SupportCaseNumber string
// ParseSupportCaseNumber validates a number returned by the support-case
// sequence. The number is for display; API paths use SupportCaseID.
func ParseSupportCaseNumber(value string) (SupportCaseNumber, error) {
if !supportCaseNumberPattern.MatchString(value) {
return "", invalidSupportCase("domain.ParseSupportCaseNumber", "number format is invalid")
}
return SupportCaseNumber(value), nil
}
func (number SupportCaseNumber) String() string { return string(number) }
func (number SupportCaseNumber) validFor(createdAt time.Time) bool {
matches := supportCaseNumberPattern.FindStringSubmatch(string(number))
if matches == nil || createdAt.IsZero() {
return false
}
year, err := strconv.Atoi(matches[1])
return err == nil && year == createdAt.UTC().Year()
}
// SupportCaseType selects the allowed reference and response target.
type SupportCaseType string
const (
SupportCaseTypeSupport SupportCaseType = "support"
SupportCaseTypeComplaint SupportCaseType = "complaint"
SupportCaseTypeGradeAppeal SupportCaseType = "grade_appeal"
SupportCaseTypeAnticheatAppeal SupportCaseType = "anticheat_appeal"
SupportCaseTypeManualAssessment SupportCaseType = "manual_assessment"
)
func (caseType SupportCaseType) IsKnown() bool {
switch caseType {
case SupportCaseTypeSupport, SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal,
SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment:
return true
default:
return false
}
}
func (caseType SupportCaseType) routesToExpert() bool {
return caseType == SupportCaseTypeGradeAppeal || caseType == SupportCaseTypeAnticheatAppeal ||
caseType == SupportCaseTypeManualAssessment
}
// SupportCaseStatus is the public processing state of a case.
type SupportCaseStatus string
const (
SupportCaseStatusSubmitted SupportCaseStatus = "submitted"
SupportCaseStatusInReview SupportCaseStatus = "in_review"
SupportCaseStatusWaitingForUser SupportCaseStatus = "waiting_for_user"
SupportCaseStatusWaitingExpert SupportCaseStatus = "waiting_expert"
SupportCaseStatusResolved SupportCaseStatus = "resolved"
SupportCaseStatusClosed SupportCaseStatus = "closed"
)
func (status SupportCaseStatus) IsKnown() bool {
switch status {
case SupportCaseStatusSubmitted, SupportCaseStatusInReview, SupportCaseStatusWaitingForUser,
SupportCaseStatusWaitingExpert, SupportCaseStatusResolved, SupportCaseStatusClosed:
return true
default:
return false
}
}
func (status SupportCaseStatus) IsTerminal() bool {
return status == SupportCaseStatusResolved || status == SupportCaseStatusClosed
}
// SupportCaseObjectType is the type of a reference stored with a case. The
// case stores only this value and the identifier, never the referenced data.
type SupportCaseObjectType string
const (
SupportCaseObjectAssessmentAttempt SupportCaseObjectType = "assessment_attempt"
SupportCaseObjectOrganization SupportCaseObjectType = "organization"
SupportCaseObjectInvitation SupportCaseObjectType = "invitation"
SupportCaseObjectSupportCase SupportCaseObjectType = "support_case"
)
func (objectType SupportCaseObjectType) IsKnown() bool {
switch objectType {
case SupportCaseObjectAssessmentAttempt, SupportCaseObjectOrganization,
SupportCaseObjectInvitation, SupportCaseObjectSupportCase:
return true
default:
return false
}
}
// SupportCaseReference is a private reference to the object a case concerns.
type SupportCaseReference struct {
Type SupportCaseObjectType `json:"type"`
ID uuid.UUID `json:"id"`
}
func (SupportCaseReference) String() string { return "[support case reference]" }
func (SupportCaseReference) GoString() string { return "[support case reference]" }
func (SupportCaseReference) Format(state fmt.State, _ rune) {
writeRedacted(state, "[support case reference]")
}
func (reference SupportCaseReference) LogValue() slog.Value {
return slog.StringValue(string(reference.Type))
}
// SupportCaseAssessmentTarget is the specialization and grade discussed by a
// case. It does not assert that the user has that grade.
type SupportCaseAssessmentTarget struct {
Specialization SpecializationCode `json:"specialization"`
Grade GradeCode `json:"grade"`
}
// SupportCaseComplaintReason is the ground of a candidate complaint.
type SupportCaseComplaintReason string
const (
SupportComplaintOrganizationConduct SupportCaseComplaintReason = "organization_conduct"
SupportComplaintOfferContent SupportCaseComplaintReason = "offer_content"
SupportComplaintSalaryTermsViolation SupportCaseComplaintReason = "salary_terms_violation"
SupportComplaintDataDisclosure SupportCaseComplaintReason = "data_disclosure"
SupportComplaintOther SupportCaseComplaintReason = "other"
)
func (reason SupportCaseComplaintReason) IsKnown() bool {
switch reason {
case SupportComplaintOrganizationConduct, SupportComplaintOfferContent,
SupportComplaintSalaryTermsViolation, SupportComplaintDataDisclosure, SupportComplaintOther:
return true
default:
return false
}
}
// SupportResponseTargetKind labels an operational goal. It is never a legal
// deadline.
type SupportResponseTargetKind string
const SupportResponseTargetOperationalGoal SupportResponseTargetKind = "operational_goal"
// SupportResponseTargetSnapshot is the persistence form of a response target.
// The late flag is derived for each read from AnsweredAt or the current time.
type SupportResponseTargetSnapshot struct {
BusinessDays BusinessDays `json:"business_days"`
DueAt time.Time `json:"due_at"`
AnsweredAt *time.Time `json:"answered_at,omitempty"`
PolicyVersion int32 `json:"policy_version"`
CalendarVersion int32 `json:"calendar_version"`
}
// SupportResponseTarget is an immutable operational target fixed at case
// creation.
type SupportResponseTarget struct {
snapshot SupportResponseTargetSnapshot
}
func NewSupportResponseTarget(snapshot SupportResponseTargetSnapshot) (SupportResponseTarget, error) {
const location = "domain.NewSupportResponseTarget"
snapshot = cloneSupportResponseTargetSnapshot(snapshot)
if snapshot.BusinessDays < 1 || snapshot.BusinessDays > 60 || snapshot.DueAt.IsZero() ||
snapshot.PolicyVersion < 1 || snapshot.CalendarVersion < 1 {
return SupportResponseTarget{}, invalidSupportCase(location, "target days, due time, policy version, and calendar version must be valid")
}
if snapshot.AnsweredAt != nil && snapshot.AnsweredAt.IsZero() {
return SupportResponseTarget{}, invalidSupportCase(location, "answered time must be set when present")
}
return SupportResponseTarget{snapshot: cloneSupportResponseTargetSnapshot(snapshot)}, nil
}
func (target SupportResponseTarget) Kind() SupportResponseTargetKind {
return SupportResponseTargetOperationalGoal
}
func (target SupportResponseTarget) BusinessDays() BusinessDays { return target.snapshot.BusinessDays }
func (target SupportResponseTarget) DueAt() time.Time { return target.snapshot.DueAt }
func (target SupportResponseTarget) PolicyVersion() int32 { return target.snapshot.PolicyVersion }
func (target SupportResponseTarget) BusinessCalendarVersion() int32 {
return target.snapshot.CalendarVersion
}
func (target SupportResponseTarget) AnsweredAt() *time.Time {
return cloneTimePointer(target.snapshot.AnsweredAt)
}
func (target SupportResponseTarget) IsLate(at time.Time) bool {
if target.IsZero() || at.IsZero() {
return false
}
if target.snapshot.AnsweredAt != nil {
return target.snapshot.AnsweredAt.After(target.snapshot.DueAt)
}
return at.After(target.snapshot.DueAt)
}
func (target SupportResponseTarget) Snapshot() SupportResponseTargetSnapshot {
return cloneSupportResponseTargetSnapshot(target.snapshot)
}
func (target SupportResponseTarget) IsZero() bool { return target.snapshot.DueAt.IsZero() }
// SupportCaseDecisionOutcome is the public outcome of a resolved case.
type SupportCaseDecisionOutcome string
const (
SupportCaseDecisionUpheld SupportCaseDecisionOutcome = "upheld"
SupportCaseDecisionPartiallyUpheld SupportCaseDecisionOutcome = "partially_upheld"
SupportCaseDecisionNotUpheld SupportCaseDecisionOutcome = "not_upheld"
SupportCaseDecisionAnswered SupportCaseDecisionOutcome = "answered"
SupportCaseDecisionAssessed SupportCaseDecisionOutcome = "assessed"
)
func (outcome SupportCaseDecisionOutcome) IsKnown() bool {
switch outcome {
case SupportCaseDecisionUpheld, SupportCaseDecisionPartiallyUpheld,
SupportCaseDecisionNotUpheld, SupportCaseDecisionAnswered, SupportCaseDecisionAssessed:
return true
default:
return false
}
}
// SupportCaseDecisionSnapshot is the public decision data persisted with a
// resolved case. It has no staff identity or internal note.
type SupportCaseDecisionSnapshot struct {
Outcome SupportCaseDecisionOutcome `json:"outcome"`
Reason string `json:"reason"`
DecidedAt time.Time `json:"decided_at"`
}
func (SupportCaseDecisionSnapshot) String() string { return redactedSupportCaseDecision }
func (SupportCaseDecisionSnapshot) GoString() string { return redactedSupportCaseDecision }
func (SupportCaseDecisionSnapshot) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCaseDecision)
}
func (snapshot SupportCaseDecisionSnapshot) LogValue() slog.Value {
return slog.StringValue(string(snapshot.Outcome))
}
// SupportCaseDecision is an immutable public decision.
type SupportCaseDecision struct {
snapshot SupportCaseDecisionSnapshot
}
func NewSupportCaseDecision(snapshot SupportCaseDecisionSnapshot) (SupportCaseDecision, error) {
const location = "domain.NewSupportCaseDecision"
snapshot.DecidedAt = canonicalSupportTime(snapshot.DecidedAt)
if !snapshot.Outcome.IsKnown() || !validSupportCaseText(snapshot.Reason, maxSupportCasePublicTextRunes) || snapshot.DecidedAt.IsZero() {
return SupportCaseDecision{}, invalidSupportCase(location, "outcome, public reason, or decision time is invalid")
}
return SupportCaseDecision{snapshot: snapshot}, nil
}
func (decision SupportCaseDecision) Outcome() SupportCaseDecisionOutcome {
return decision.snapshot.Outcome
}
func (decision SupportCaseDecision) Reason() string { return decision.snapshot.Reason }
func (decision SupportCaseDecision) DecidedAt() time.Time { return decision.snapshot.DecidedAt }
func (decision SupportCaseDecision) Snapshot() SupportCaseDecisionSnapshot { return decision.snapshot }
func (decision SupportCaseDecision) IsZero() bool { return decision.snapshot.DecidedAt.IsZero() }
func (SupportCaseDecision) String() string { return redactedSupportCaseDecision }
func (SupportCaseDecision) GoString() string { return redactedSupportCaseDecision }
func (SupportCaseDecision) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCaseDecision)
}
func (decision SupportCaseDecision) LogValue() slog.Value {
return slog.StringValue(string(decision.snapshot.Outcome))
}
// SupportCaseEventKind identifies one public history event.
type SupportCaseEventKind string
const (
SupportCaseEventCreated SupportCaseEventKind = "created"
SupportCaseEventStatusChanged SupportCaseEventKind = "status_changed"
SupportCaseEventReply SupportCaseEventKind = "reply"
SupportCaseEventDecision SupportCaseEventKind = "decision"
)
func (kind SupportCaseEventKind) IsKnown() bool {
switch kind {
case SupportCaseEventCreated, SupportCaseEventStatusChanged, SupportCaseEventReply, SupportCaseEventDecision:
return true
default:
return false
}
}
// SupportCaseActorKind names only the kind of actor, never the staff member.
type SupportCaseActorKind string
const (
SupportCaseActorUser SupportCaseActorKind = "user"
SupportCaseActorSupport SupportCaseActorKind = "support"
SupportCaseActorSystem SupportCaseActorKind = "system"
)
func (actor SupportCaseActorKind) IsKnown() bool {
return actor == SupportCaseActorUser || actor == SupportCaseActorSupport || actor == SupportCaseActorSystem
}
// SupportCaseEventSnapshot is the public, immutable form of one history event.
type SupportCaseEventSnapshot struct {
Sequence int32 `json:"sequence"`
Kind SupportCaseEventKind `json:"kind"`
Actor SupportCaseActorKind `json:"actor"`
OccurredAt time.Time `json:"occurred_at"`
Status *SupportCaseStatus `json:"status,omitempty"`
Message *string `json:"message,omitempty"`
}
func (SupportCaseEventSnapshot) String() string { return redactedSupportCaseEvent }
func (SupportCaseEventSnapshot) GoString() string { return redactedSupportCaseEvent }
func (SupportCaseEventSnapshot) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCaseEvent)
}
func (event SupportCaseEventSnapshot) LogValue() slog.Value {
return slog.GroupValue(
slog.Int("sequence", int(event.Sequence)),
slog.String("kind", string(event.Kind)),
slog.String("actor", string(event.Actor)),
)
}
// SupportCaseEvent is one public event. It deliberately has no actor ID,
// assignment, evidence, or internal-note field.
type SupportCaseEvent struct {
snapshot SupportCaseEventSnapshot
}
func RestoreSupportCaseEvent(snapshot SupportCaseEventSnapshot) (SupportCaseEvent, error) {
const location = "domain.RestoreSupportCaseEvent"
snapshot = cloneSupportCaseEventSnapshot(snapshot)
if err := validateSupportCaseEvent(location, snapshot); err != nil {
return SupportCaseEvent{}, err
}
return SupportCaseEvent{snapshot: cloneSupportCaseEventSnapshot(snapshot)}, nil
}
func (event SupportCaseEvent) Snapshot() SupportCaseEventSnapshot {
return cloneSupportCaseEventSnapshot(event.snapshot)
}
func (event SupportCaseEvent) String() string { return redactedSupportCaseEvent }
func (event SupportCaseEvent) GoString() string { return redactedSupportCaseEvent }
func (event SupportCaseEvent) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCaseEvent)
}
func (event SupportCaseEvent) LogValue() slog.Value {
return slog.GroupValue(
slog.Int("sequence", int(event.snapshot.Sequence)),
slog.String("kind", string(event.snapshot.Kind)),
slog.String("actor", string(event.snapshot.Actor)),
)
}
// SupportCaseSnapshot is the persistence projection of one private case. Its
// description and public messages may contain personal data and are redacted
// by its formatting and logging methods.
type SupportCaseSnapshot struct {
ID SupportCaseID `json:"id"`
Number SupportCaseNumber `json:"number"`
OwnerID uuid.UUID `json:"owner_id"`
Type SupportCaseType `json:"type"`
Status SupportCaseStatus `json:"status"`
Description string `json:"description"`
Object *SupportCaseReference `json:"object,omitempty"`
AssessmentTarget *SupportCaseAssessmentTarget `json:"assessment_target,omitempty"`
ComplaintReason *SupportCaseComplaintReason `json:"complaint_reason,omitempty"`
RubricVersion *int32 `json:"rubric_version,omitempty"`
RubricOpeningID *uuid.UUID `json:"rubric_opening_id,omitempty"`
RubricPolicyID *PolicyVersionID `json:"rubric_policy_version_id,omitempty"`
ResponseTarget SupportResponseTargetSnapshot `json:"response_target"`
Decision *SupportCaseDecisionSnapshot `json:"decision,omitempty"`
History []SupportCaseEventSnapshot `json:"history"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (SupportCaseSnapshot) String() string { return redactedSupportCase }
func (SupportCaseSnapshot) GoString() string { return redactedSupportCase }
func (SupportCaseSnapshot) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCase)
}
func (snapshot SupportCaseSnapshot) LogValue() slog.Value {
return slog.GroupValue(
slog.String("case_id", snapshot.ID.String()),
slog.String("number", snapshot.Number.String()),
slog.String("type", string(snapshot.Type)),
slog.String("status", string(snapshot.Status)),
)
}
// NewSupportCaseInput is the user-stated content and server-resolved context
// for one new case. OwnerID is taken from the authenticated session. Object
// content, status, decision, and staff identity are not accepted here.
type NewSupportCaseInput struct {
Number SupportCaseNumber
OwnerID uuid.UUID
Type SupportCaseType
Description string
Object *SupportCaseReference
AssessmentTarget *SupportCaseAssessmentTarget
ComplaintReason *SupportCaseComplaintReason
RubricVersion *int32
RubricOpeningID *uuid.UUID
RubricPolicyID *PolicyVersionID
ResponseTarget SupportResponseTarget
CreatedAt time.Time
}
func (NewSupportCaseInput) String() string { return redactedSupportCase }
func (NewSupportCaseInput) GoString() string { return redactedSupportCase }
func (NewSupportCaseInput) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCase)
}
func (NewSupportCaseInput) LogValue() slog.Value { return slog.StringValue(redactedSupportCase) }
// SupportCase is one account-owned case with immutable public creation
// history. Later status and decision commands will restore a new snapshot.
type SupportCase struct {
snapshot SupportCaseSnapshot
}
// NewSupportCase assigns a case ID and creates the initial public event(s).
// Appeals and manual requests enter waiting_expert in the same creation
// history; no grade, attempt, or consent is created as a side effect.
func NewSupportCase(input NewSupportCaseInput) (SupportCase, error) {
const location = "domain.NewSupportCase"
if err := ValidateSupportCaseRequest(input); err != nil {
return SupportCase{}, fmt.Errorf("%s - validate request: %w", location, err)
}
if input.CreatedAt.IsZero() {
return SupportCase{}, invalidSupportCase(location, "creation time must be set")
}
id, err := NewSupportCaseID()
if err != nil {
return SupportCase{}, fmt.Errorf("%s - assign ID: %w", location, err)
}
createdAt := canonicalSupportTime(input.CreatedAt)
created := SupportCaseEventSnapshot{
Sequence: 1, Kind: SupportCaseEventCreated, Actor: SupportCaseActorUser,
OccurredAt: createdAt, Status: supportCaseStatusPointer(SupportCaseStatusSubmitted),
}
history := []SupportCaseEventSnapshot{created}
status := SupportCaseStatusSubmitted
if input.Type.routesToExpert() {
status = SupportCaseStatusWaitingExpert
history = append(history, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSystem,
OccurredAt: createdAt, Status: supportCaseStatusPointer(status),
})
}
snapshot := SupportCaseSnapshot{
ID: id, Number: input.Number, OwnerID: input.OwnerID, Type: input.Type, Status: status,
Description: input.Description, Object: input.Object, AssessmentTarget: input.AssessmentTarget,
ComplaintReason: input.ComplaintReason, RubricVersion: input.RubricVersion,
RubricOpeningID: input.RubricOpeningID, RubricPolicyID: input.RubricPolicyID,
ResponseTarget: input.ResponseTarget.Snapshot(), History: history,
CreatedAt: createdAt, UpdatedAt: createdAt,
}
return RestoreSupportCase(snapshot)
}
// ValidateSupportCaseRequest checks client-supplied fields before resolving
// referenced objects. Ownership and object state remain use-case concerns.
func ValidateSupportCaseRequest(input NewSupportCaseInput) error {
const location = "domain.ValidateSupportCaseRequest"
if !input.Type.IsKnown() {
return &SupportCaseFieldError{Pointer: "/type", Reason: "is not supported"}
}
if !validSupportCaseDescription(input.Description) {
return &SupportCaseFieldError{Pointer: "/description", Reason: "must contain non-whitespace text"}
}
if err := validateSupportCaseRequestObject(input); err != nil {
return err
}
if err := validateSupportCaseRequestAssessmentTarget(input.AssessmentTarget); err != nil {
return err
}
if err := validateSupportCaseRequestComplaint(input.Type, input.Object, input.ComplaintReason); err != nil {
return err
}
snapshot := SupportCaseSnapshot{
Type: input.Type, Description: input.Description, Object: input.Object,
AssessmentTarget: input.AssessmentTarget, ComplaintReason: input.ComplaintReason,
RubricVersion: input.RubricVersion, RubricOpeningID: input.RubricOpeningID,
RubricPolicyID: input.RubricPolicyID,
}
if err := validateSupportCaseFields(snapshot); err != nil {
return fmt.Errorf("%s - validate fields: %w", location, err)
}
return nil
}
func validateSupportCaseRequestObject(input NewSupportCaseInput) error {
if input.Object == nil {
return nil
}
switch {
case !input.Object.Type.IsKnown():
return &SupportCaseFieldError{Pointer: "/object/type", Reason: "is not supported"}
case input.Object.ID == uuid.Nil:
return &SupportCaseFieldError{Pointer: "/object/id", Reason: "must be set"}
case !supportObjectAllowed(input.Type, input.Object.Type):
return &SupportCaseFieldError{Pointer: "/object/type", Reason: "does not apply to this case type"}
default:
return nil
}
}
func validateSupportCaseRequestAssessmentTarget(target *SupportCaseAssessmentTarget) error {
if target == nil {
return nil
}
if !target.Specialization.IsKnown() {
return &SupportCaseFieldError{Pointer: "/assessment_target/specialization", Reason: "is not supported"}
}
if !target.Grade.IsKnown() {
return &SupportCaseFieldError{Pointer: "/assessment_target/grade", Reason: "is not supported"}
}
return nil
}
func validateSupportCaseRequestComplaint(
caseType SupportCaseType,
object *SupportCaseReference,
reason *SupportCaseComplaintReason,
) error {
if reason != nil && !reason.IsKnown() {
return &SupportCaseFieldError{Pointer: "/complaint_reason", Reason: "is not supported"}
}
if caseType == SupportCaseTypeComplaint && requiresInvitation(reason) &&
(object == nil || object.Type != SupportCaseObjectInvitation) {
return &SupportCaseFieldError{Pointer: "/object/type", Reason: "must be invitation for this complaint reason"}
}
return nil
}
// RestoreSupportCase validates a case read from storage before exposing it to
// an owner. A case remains readable by its owner even when its referenced
// object later changes state or access.
func RestoreSupportCase(snapshot SupportCaseSnapshot) (SupportCase, error) {
const location = "domain.RestoreSupportCase"
snapshot = cloneSupportCaseSnapshot(snapshot)
if err := validateSupportCaseSnapshot(location, snapshot); err != nil {
return SupportCase{}, err
}
return SupportCase{snapshot: cloneSupportCaseSnapshot(snapshot)}, nil
}
func (supportCase SupportCase) Snapshot() SupportCaseSnapshot {
return cloneSupportCaseSnapshot(supportCase.snapshot)
}
func (supportCase SupportCase) ID() SupportCaseID { return supportCase.snapshot.ID }
func (supportCase SupportCase) Number() SupportCaseNumber { return supportCase.snapshot.Number }
func (supportCase SupportCase) OwnerID() uuid.UUID { return supportCase.snapshot.OwnerID }
func (supportCase SupportCase) Type() SupportCaseType { return supportCase.snapshot.Type }
func (supportCase SupportCase) Status() SupportCaseStatus { return supportCase.snapshot.Status }
func (supportCase SupportCase) Description() string { return supportCase.snapshot.Description }
func (supportCase SupportCase) CreatedAt() time.Time { return supportCase.snapshot.CreatedAt }
func (supportCase SupportCase) UpdatedAt() time.Time { return supportCase.snapshot.UpdatedAt }
func (supportCase SupportCase) IsZero() bool { return supportCase.snapshot.ID.IsZero() }
func (supportCase SupportCase) ResponseTarget() SupportResponseTarget {
target, _ := NewSupportResponseTarget(supportCase.snapshot.ResponseTarget)
return target
}
func (supportCase SupportCase) Object() *SupportCaseReference {
return cloneSupportCaseReference(supportCase.snapshot.Object)
}
func (supportCase SupportCase) AssessmentTarget() *SupportCaseAssessmentTarget {
return cloneSupportCaseAssessmentTarget(supportCase.snapshot.AssessmentTarget)
}
func (supportCase SupportCase) ComplaintReason() *SupportCaseComplaintReason {
return cloneComplaintReason(supportCase.snapshot.ComplaintReason)
}
func (supportCase SupportCase) RubricVersion() *int32 {
return cloneInt32Pointer(supportCase.snapshot.RubricVersion)
}
func (supportCase SupportCase) Decision() *SupportCaseDecision {
if supportCase.snapshot.Decision == nil {
return nil
}
decision, err := NewSupportCaseDecision(*supportCase.snapshot.Decision)
if err != nil {
return nil
}
return &decision
}
func (supportCase SupportCase) History() []SupportCaseEvent {
events := make([]SupportCaseEvent, len(supportCase.snapshot.History))
for index, snapshot := range supportCase.snapshot.History {
events[index] = SupportCaseEvent{snapshot: cloneSupportCaseEventSnapshot(snapshot)}
}
return events
}
// Summary returns the list projection, which omits the description and event
// history so a list query need not load either field.
func (supportCase SupportCase) Summary() SupportCaseSummary {
var decisionOutcome *SupportCaseDecisionOutcome
if supportCase.snapshot.Decision != nil {
decisionOutcome = supportCaseDecisionOutcomePointer(supportCase.snapshot.Decision.Outcome)
}
return SupportCaseSummary{
ID: supportCase.snapshot.ID, Number: supportCase.snapshot.Number, Type: supportCase.snapshot.Type,
Status: supportCase.snapshot.Status, Object: cloneSupportCaseReference(supportCase.snapshot.Object),
AssessmentTarget: cloneSupportCaseAssessmentTarget(supportCase.snapshot.AssessmentTarget),
ResponseTarget: cloneSupportResponseTargetSnapshot(supportCase.snapshot.ResponseTarget),
DecisionOutcome: decisionOutcome, CreatedAt: supportCase.snapshot.CreatedAt, UpdatedAt: supportCase.snapshot.UpdatedAt,
}
}
func (SupportCase) String() string { return redactedSupportCase }
func (SupportCase) GoString() string { return redactedSupportCase }
func (SupportCase) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedSupportCase)
}
func (supportCase SupportCase) LogValue() slog.Value { return supportCase.snapshot.LogValue() }
// SupportCaseSummary is a list item without description or event history.
type SupportCaseSummary struct {
ID SupportCaseID
Number SupportCaseNumber
Type SupportCaseType
Status SupportCaseStatus
Object *SupportCaseReference
AssessmentTarget *SupportCaseAssessmentTarget
ResponseTarget SupportResponseTargetSnapshot
DecisionOutcome *SupportCaseDecisionOutcome
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreSupportCaseSummary validates the projection returned by the
// owner-scoped list query. It cannot validate private fields omitted from the
// query, so checks stay limited to the public summary contract.
func RestoreSupportCaseSummary(summary SupportCaseSummary) (SupportCaseSummary, error) {
const location = "domain.RestoreSupportCaseSummary"
summary = cloneSupportCaseSummary(summary)
if !validSupportCaseSummaryIdentity(summary) {
return SupportCaseSummary{}, invalidSupportCase(location, "identity, status, or timestamps are invalid")
}
if !validSupportCaseSummaryObject(summary) {
return SupportCaseSummary{}, invalidSupportCase(location, "object reference is invalid")
}
if !validSupportCaseSummaryAssessmentTarget(summary) {
return SupportCaseSummary{}, invalidSupportCase(location, "assessment target is invalid")
}
if err := validateSupportCaseSummaryFields(summary); err != nil {
return SupportCaseSummary{}, err
}
if !validSupportCaseSummaryResponseTarget(summary) {
return SupportCaseSummary{}, invalidSupportCase(location, "response target is invalid")
}
if err := validateSupportCaseSummaryDecision(summary); err != nil {
return SupportCaseSummary{}, err
}
return summary, nil
}
func validSupportCaseSummaryIdentity(summary SupportCaseSummary) bool {
return !summary.ID.IsZero() && summary.Number.validFor(summary.CreatedAt) && summary.Type.IsKnown() &&
summary.Status.IsKnown() && !summary.CreatedAt.IsZero() && !summary.UpdatedAt.Before(summary.CreatedAt)
}
func validSupportCaseSummaryObject(summary SupportCaseSummary) bool {
if summary.Object == nil {
return true
}
return summary.Object.Type.IsKnown() && summary.Object.ID != uuid.Nil &&
supportObjectAllowed(summary.Type, summary.Object.Type)
}
func validSupportCaseSummaryAssessmentTarget(summary SupportCaseSummary) bool {
if summary.AssessmentTarget == nil {
return true
}
return summary.AssessmentTarget.Specialization.IsKnown() && summary.AssessmentTarget.Grade.IsKnown()
}
func validateSupportCaseSummaryFields(summary SupportCaseSummary) error {
const location = "domain.RestoreSupportCaseSummary"
switch summary.Type {
case SupportCaseTypeSupport:
if summary.AssessmentTarget != nil {
return invalidSupportCase(location, "support summary has an assessment target")
}
case SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal:
if summary.Object == nil || summary.AssessmentTarget != nil {
return invalidSupportCase(location, "summary requires its matching object reference")
}
case SupportCaseTypeManualAssessment:
if summary.AssessmentTarget == nil || summary.Object != nil && summary.Object.Type != SupportCaseObjectAssessmentAttempt {
return invalidSupportCase(location, "manual assessment summary fields are invalid")
}
}
return nil
}
func validSupportCaseSummaryResponseTarget(summary SupportCaseSummary) bool {
_, err := NewSupportResponseTarget(summary.ResponseTarget)
return err == nil && !summary.ResponseTarget.DueAt.Before(summary.CreatedAt)
}
func validateSupportCaseSummaryDecision(summary SupportCaseSummary) error {
const location = "domain.RestoreSupportCaseSummary"
if (summary.Status == SupportCaseStatusResolved) != (summary.DecisionOutcome != nil) {
return invalidSupportCase(location, "decision summary does not match status")
}
if summary.DecisionOutcome == nil {
return nil
}
if !summary.DecisionOutcome.IsKnown() || !supportDecisionAllowed(summary.Type, *summary.DecisionOutcome) {
return invalidSupportCase(location, "decision outcome does not apply to the case type")
}
return nil
}
func (SupportCaseSummary) String() string { return "[support case summary]" }
func (SupportCaseSummary) GoString() string { return "[support case summary]" }
func (SupportCaseSummary) Format(state fmt.State, _ rune) {
writeRedacted(state, "[support case summary]")
}
// SupportCaseCreateOutcomeKind is the small set of responses retained for an
// idempotent create. Failure outcomes carry no object or reference details.
type SupportCaseCreateOutcomeKind string
const (
SupportCaseCreateOutcomeCreated SupportCaseCreateOutcomeKind = "created"
SupportCaseCreateOutcomeNotFound SupportCaseCreateOutcomeKind = "not_found"
SupportCaseCreateOutcomeStateConflict SupportCaseCreateOutcomeKind = "state_conflict"
)
// SupportCaseCreateOutcomeSnapshot is the immutable result replayed for a
// live idempotency scope. It never stores a foreign object identifier in a
// not_found outcome.
type SupportCaseCreateOutcomeSnapshot struct {
Kind SupportCaseCreateOutcomeKind `json:"kind"`
Case *SupportCaseSnapshot `json:"case,omitempty"`
TargetWasLate bool `json:"target_was_late"`
}
// SupportCaseCreateOutcome is the typed result persisted with a create key.
type SupportCaseCreateOutcome struct {
snapshot SupportCaseCreateOutcomeSnapshot
}
func NewSupportCaseCreatedOutcome(supportCase SupportCase) (SupportCaseCreateOutcome, error) {
if supportCase.IsZero() {
return SupportCaseCreateOutcome{}, invalidSupportCase("domain.NewSupportCaseCreatedOutcome", "case must be set")
}
snapshot := supportCase.Snapshot()
if !isInitialSupportCaseSnapshot(snapshot) {
return SupportCaseCreateOutcome{}, invalidSupportCase("domain.NewSupportCaseCreatedOutcome", "case must be its original creation snapshot")
}
return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{
Kind: SupportCaseCreateOutcomeCreated, Case: &snapshot,
TargetWasLate: supportCase.ResponseTarget().IsLate(supportCase.CreatedAt()),
}}, nil
}
func isInitialSupportCaseSnapshot(snapshot SupportCaseSnapshot) bool {
initialStatus := SupportCaseStatusSubmitted
initialEvents := 1
if snapshot.Type.routesToExpert() {
initialStatus = SupportCaseStatusWaitingExpert
initialEvents = 2
}
return snapshot.Status == initialStatus && snapshot.CreatedAt.Equal(snapshot.UpdatedAt) &&
len(snapshot.History) == initialEvents && snapshot.Decision == nil && snapshot.ResponseTarget.AnsweredAt == nil
}
func NewSupportCaseNotFoundOutcome() SupportCaseCreateOutcome {
return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeNotFound}}
}
func NewSupportCaseStateConflictOutcome() SupportCaseCreateOutcome {
return SupportCaseCreateOutcome{snapshot: SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeStateConflict}}
}
func RestoreSupportCaseCreateOutcome(snapshot SupportCaseCreateOutcomeSnapshot) (SupportCaseCreateOutcome, error) {
const location = "domain.RestoreSupportCaseCreateOutcome"
switch snapshot.Kind {
case SupportCaseCreateOutcomeCreated:
if snapshot.Case == nil {
return SupportCaseCreateOutcome{}, invalidSupportCase(location, "created outcome requires its original case snapshot")
}
if _, err := RestoreSupportCase(*snapshot.Case); err != nil {
return SupportCaseCreateOutcome{}, fmt.Errorf("%s - restore original case: %w", location, err)
}
case SupportCaseCreateOutcomeNotFound, SupportCaseCreateOutcomeStateConflict:
if snapshot.Case != nil || snapshot.TargetWasLate {
return SupportCaseCreateOutcome{}, invalidSupportCase(location, "failure outcome cannot contain a case snapshot")
}
default:
return SupportCaseCreateOutcome{}, invalidSupportCase(location, "outcome kind is unknown")
}
return SupportCaseCreateOutcome{snapshot: cloneSupportCaseCreateOutcomeSnapshot(snapshot)}, nil
}
func (outcome SupportCaseCreateOutcome) Kind() SupportCaseCreateOutcomeKind {
return outcome.snapshot.Kind
}
func (outcome SupportCaseCreateOutcome) Case() (SupportCase, bool) {
if outcome.snapshot.Kind != SupportCaseCreateOutcomeCreated || outcome.snapshot.Case == nil {
return SupportCase{}, false
}
supportCase, err := RestoreSupportCase(*outcome.snapshot.Case)
if err != nil {
return SupportCase{}, false
}
return supportCase, true
}
// CreationTargetWasLate reports the target's state at the instant the case
// was created. A 201 replay must use this stored value, while a current GET
// evaluates ResponseTarget().IsLate(now).
func (outcome SupportCaseCreateOutcome) CreationTargetWasLate() (bool, bool) {
if outcome.snapshot.Kind != SupportCaseCreateOutcomeCreated || outcome.snapshot.Case == nil {
return false, false
}
return outcome.snapshot.TargetWasLate, true
}
func (outcome SupportCaseCreateOutcome) Snapshot() SupportCaseCreateOutcomeSnapshot {
return cloneSupportCaseCreateOutcomeSnapshot(outcome.snapshot)
}
func (outcome SupportCaseCreateOutcome) IsZero() bool { return outcome.snapshot.Kind == "" }
func (SupportCaseCreateOutcome) String() string { return "[support case create outcome]" }
func (SupportCaseCreateOutcome) GoString() string { return "[support case create outcome]" }
func (SupportCaseCreateOutcome) Format(state fmt.State, _ rune) {
writeRedacted(state, "[support case create outcome]")
}
func (outcome SupportCaseCreateOutcome) LogValue() slog.Value {
return slog.StringValue(string(outcome.snapshot.Kind))
}
func validateSupportCaseSnapshot(location string, snapshot SupportCaseSnapshot) error {
if err := validateSupportCaseIdentityAndContent(location, snapshot); err != nil {
return err
}
if err := validateSupportCaseFields(snapshot); err != nil {
return fmt.Errorf("%s - validate case fields: %w", location, err)
}
if err := validateSupportCaseTarget(location, snapshot); err != nil {
return err
}
if err := validateSupportCaseHistory(location, snapshot); err != nil {
return err
}
if err := validateSupportCaseDecision(location, snapshot); err != nil {
return err
}
return nil
}
func validateSupportCaseIdentityAndContent(location string, snapshot SupportCaseSnapshot) error {
if snapshot.ID.IsZero() || snapshot.OwnerID == uuid.Nil {
return invalidSupportCase(location, "case and owner identifiers must be set")
}
if !snapshot.Number.validFor(snapshot.CreatedAt) {
return invalidSupportCase(location, "number must match the UTC creation year")
}
if !snapshot.Type.IsKnown() || !snapshot.Status.IsKnown() {
return invalidSupportCase(location, "case type or status is unknown")
}
if !validSupportCaseDescription(snapshot.Description) {
return invalidSupportCase(location, "description must be valid, non-blank text of at most 4000 characters")
}
if snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt) {
return invalidSupportCase(location, "creation and update times are invalid")
}
if len(snapshot.History) == 0 || len(snapshot.History) > maxSupportCaseEvents ||
!snapshot.Status.IsTerminal() && len(snapshot.History) >= maxSupportCaseEvents {
return invalidSupportCase(location, "public history must leave room for a terminal event and contain at most 200 events")
}
return nil
}
func validateSupportCaseTarget(location string, snapshot SupportCaseSnapshot) error {
target, err := NewSupportResponseTarget(snapshot.ResponseTarget)
if err != nil {
return fmt.Errorf("%s - validate response target: %w", location, err)
}
if target.DueAt().Before(snapshot.CreatedAt) {
return invalidSupportCase(location, "response target cannot precede creation")
}
if answeredAt := target.AnsweredAt(); answeredAt != nil && answeredAt.Before(snapshot.CreatedAt) {
return invalidSupportCase(location, "answer time cannot precede creation")
}
return nil
}
func validateSupportCaseDecision(location string, snapshot SupportCaseSnapshot) error {
if snapshot.Decision != nil {
decision, err := NewSupportCaseDecision(*snapshot.Decision)
if err != nil {
return fmt.Errorf("%s - validate decision: %w", location, err)
}
if !supportDecisionAllowed(snapshot.Type, decision.Outcome()) {
return invalidSupportCase(location, "decision outcome does not apply to this case type")
}
}
switch snapshot.Status {
case SupportCaseStatusResolved:
return validateResolvedSupportCaseDecision(location, snapshot)
case SupportCaseStatusClosed:
if snapshot.Decision != nil {
return invalidSupportCase(location, "only a resolved case may contain a decision")
}
return validateClosedSupportCase(location, snapshot)
case SupportCaseStatusSubmitted, SupportCaseStatusInReview,
SupportCaseStatusWaitingForUser, SupportCaseStatusWaitingExpert:
if snapshot.Decision != nil {
return invalidSupportCase(location, "only a resolved case may contain a decision")
}
}
return nil
}
func validateResolvedSupportCaseDecision(location string, snapshot SupportCaseSnapshot) error {
if snapshot.Decision == nil {
return invalidSupportCase(location, "a resolved case requires a public decision")
}
last := snapshot.History[len(snapshot.History)-1]
if last.Kind != SupportCaseEventDecision || last.Message == nil ||
*last.Message != snapshot.Decision.Reason || !last.OccurredAt.Equal(snapshot.Decision.DecidedAt) {
return invalidSupportCase(location, "resolved case must end with its public decision event")
}
return nil
}
func validateClosedSupportCase(location string, snapshot SupportCaseSnapshot) error {
last := snapshot.History[len(snapshot.History)-1]
if last.Kind != SupportCaseEventStatusChanged || last.Status == nil ||
*last.Status != SupportCaseStatusClosed || last.Message == nil {
return invalidSupportCase(location, "closed case must end with a public closure reason")
}
return nil
}
func validateSupportCaseFields(snapshot SupportCaseSnapshot) error {
if err := validateSupportCaseObject(snapshot); err != nil {
return err
}
if err := validateSupportCaseMetadata(snapshot); err != nil {
return err
}
return validateSupportCaseTypeFields(snapshot)
}
func validateSupportCaseObject(snapshot SupportCaseSnapshot) error {
if snapshot.Object == nil {
return nil
}
if !snapshot.Object.Type.IsKnown() || snapshot.Object.ID == uuid.Nil || !supportObjectAllowed(snapshot.Type, snapshot.Object.Type) {
return invalidSupportCase("domain.RestoreSupportCase", "object type or identifier is not allowed")
}
return nil
}
func validateSupportCaseMetadata(snapshot SupportCaseSnapshot) error {
if snapshot.AssessmentTarget != nil && (!snapshot.AssessmentTarget.Specialization.IsKnown() || !snapshot.AssessmentTarget.Grade.IsKnown()) {
return invalidSupportCase("domain.RestoreSupportCase", "assessment target is not in the MVP catalog")
}
if snapshot.ComplaintReason != nil && !snapshot.ComplaintReason.IsKnown() {
return invalidSupportCase("domain.RestoreSupportCase", "complaint reason is unknown")
}
if snapshot.RubricVersion != nil && *snapshot.RubricVersion < 1 {
return invalidSupportCase("domain.RestoreSupportCase", "rubric version must be positive when present")
}
if err := validateSupportCaseRubricPin(snapshot); err != nil {
return err
}
return nil
}
func validateSupportCaseRubricPin(snapshot SupportCaseSnapshot) error {
hasVersion := snapshot.RubricVersion != nil
hasOpening := snapshot.RubricOpeningID != nil
hasPolicy := snapshot.RubricPolicyID != nil
if !hasVersion && !hasOpening && !hasPolicy {
return nil
}
if snapshot.Type != SupportCaseTypeManualAssessment || !hasVersion || !hasOpening || !hasPolicy ||
*snapshot.RubricOpeningID == uuid.Nil || snapshot.RubricPolicyID.IsZero() {
return invalidSupportCase("domain.RestoreSupportCase", "rubric version and private policy pins must be complete for a manual assessment")
}
return nil
}
func validateSupportCaseTypeFields(snapshot SupportCaseSnapshot) error {
switch snapshot.Type {
case SupportCaseTypeSupport:
return validateSupportFields(snapshot)
case SupportCaseTypeComplaint:
return validateComplaintFields(snapshot)
case SupportCaseTypeGradeAppeal:
return validateGradeAppealFields(snapshot)
case SupportCaseTypeAnticheatAppeal:
return validateAnticheatAppealFields(snapshot)
case SupportCaseTypeManualAssessment:
return validateManualAssessmentFields(snapshot)
}
return invalidSupportCase("domain.RestoreSupportCase", "case type is unknown")
}
func validateSupportFields(snapshot SupportCaseSnapshot) error {
if snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil {
return invalidSupportCase("domain.RestoreSupportCase", "support case has fields from another case type")
}
return nil
}
func validateComplaintFields(snapshot SupportCaseSnapshot) error {
if snapshot.Object == nil || snapshot.ComplaintReason == nil || snapshot.AssessmentTarget != nil || snapshot.RubricVersion != nil {
return invalidSupportCase("domain.RestoreSupportCase", "complaint requires an object and reason only")
}
if requiresInvitation(snapshot.ComplaintReason) && snapshot.Object.Type != SupportCaseObjectInvitation {
return invalidSupportCase("domain.RestoreSupportCase", "complaint reason requires an invitation reference")
}
return nil
}
func validateGradeAppealFields(snapshot SupportCaseSnapshot) error {
if snapshot.Object == nil || snapshot.AssessmentTarget != nil || snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil {
return invalidSupportCase("domain.RestoreSupportCase", "grade appeal requires an allowed object only")
}
return nil
}
func validateAnticheatAppealFields(snapshot SupportCaseSnapshot) error {
if snapshot.Object == nil || snapshot.AssessmentTarget != nil || snapshot.ComplaintReason != nil || snapshot.RubricVersion != nil {
return invalidSupportCase("domain.RestoreSupportCase", "anti-cheat appeal requires an attempt only")
}
return nil
}
func validateManualAssessmentFields(snapshot SupportCaseSnapshot) error {
if snapshot.AssessmentTarget == nil || snapshot.ComplaintReason != nil {
return invalidSupportCase("domain.RestoreSupportCase", "manual assessment requires a category and no complaint reason")
}
return nil
}
func validateSupportCaseHistory(location string, snapshot SupportCaseSnapshot) error {
if err := validateSupportCaseEventOrder(location, snapshot); err != nil {
return err
}
if err := validateSupportCaseInitialHistory(location, snapshot); err != nil {
return err
}
currentStatus := supportCaseHistoryStatus(snapshot.History)
if currentStatus != snapshot.Status || !snapshot.UpdatedAt.Equal(snapshot.History[len(snapshot.History)-1].OccurredAt) {
return invalidSupportCase(location, "case state and latest history event do not match")
}
if err := validateSupportCaseResponseTargetAnswer(location, snapshot); err != nil {
return err
}
return nil
}
func validateSupportCaseResponseTargetAnswer(location string, snapshot SupportCaseSnapshot) error {
target := snapshot.ResponseTarget
if target.CalendarVersion < 1 {
return invalidSupportCase(location, "response target calendar version must be positive")
}
if target.AnsweredAt != nil && target.AnsweredAt.After(snapshot.UpdatedAt) {
return invalidSupportCase(location, "response target answer cannot follow the case update time")
}
var firstAnswerAt *time.Time
for _, event := range snapshot.History {
if supportCaseEventMeetsTarget(snapshot.Type, event) {
occurredAt := event.OccurredAt
firstAnswerAt = &occurredAt
break
}
}
if (target.AnsweredAt == nil) != (firstAnswerAt == nil) {
return invalidSupportCase(location, "response target answer time must match the first qualifying public event")
}
if firstAnswerAt != nil && !target.AnsweredAt.Equal(*firstAnswerAt) {
return invalidSupportCase(location, "response target answer time must match the first qualifying public event")
}
return nil
}
func supportCaseEventMeetsTarget(caseType SupportCaseType, event SupportCaseEventSnapshot) bool {
switch event.Kind {
case SupportCaseEventCreated:
return false
case SupportCaseEventDecision:
return true
case SupportCaseEventStatusChanged:
return event.Status != nil && *event.Status == SupportCaseStatusClosed
case SupportCaseEventReply:
return caseType == SupportCaseTypeSupport || caseType == SupportCaseTypeComplaint
}
return false
}
func validateSupportCaseEventOrder(location string, snapshot SupportCaseSnapshot) error {
var previousAt time.Time
for index, eventSnapshot := range snapshot.History {
if err := validateSupportCaseEvent(location, eventSnapshot); err != nil {
return err
}
if eventSnapshot.Sequence != int32(index+1) || index > 0 && eventSnapshot.OccurredAt.Before(previousAt) {
return invalidSupportCase(location, "history sequence or time order is invalid")
}
if index > 0 && eventSnapshot.Kind == SupportCaseEventCreated {
return invalidSupportCase(location, "history cannot repeat the created event")
}
previousAt = eventSnapshot.OccurredAt
}
return nil
}
func validateSupportCaseInitialHistory(location string, snapshot SupportCaseSnapshot) error {
created := snapshot.History[0]
if created.Kind != SupportCaseEventCreated || created.Actor != SupportCaseActorUser ||
created.Status == nil || *created.Status != SupportCaseStatusSubmitted ||
created.Message != nil || !created.OccurredAt.Equal(snapshot.CreatedAt) {
return invalidSupportCase(location, "history must begin with the author's created event")
}
if snapshot.Type.routesToExpert() {
return validateSupportCaseExpertRoutingEvent(location, snapshot.History)
}
return nil
}
func validateSupportCaseExpertRoutingEvent(location string, history []SupportCaseEventSnapshot) error {
if len(history) < 2 {
return invalidSupportCase(location, "appeal and manual case history is missing its routing event")
}
event := history[1]
if event.Kind != SupportCaseEventStatusChanged || event.Actor != SupportCaseActorSystem ||
event.Status == nil || *event.Status != SupportCaseStatusWaitingExpert || event.Message != nil {
return invalidSupportCase(location, "appeal and manual cases require an initial expert-routing event")
}
return nil
}
func supportCaseHistoryStatus(history []SupportCaseEventSnapshot) SupportCaseStatus {
status := SupportCaseStatusSubmitted
for _, event := range history {
if event.Status != nil {
status = *event.Status
}
}
return status
}
func validateSupportCaseEvent(location string, event SupportCaseEventSnapshot) error {
if event.Sequence < 1 || !event.Kind.IsKnown() || !event.Actor.IsKnown() || event.OccurredAt.IsZero() {
return invalidSupportCase(location, "event identity or time is invalid")
}
if event.Status != nil && !event.Status.IsKnown() {
return invalidSupportCase(location, "event status is unknown")
}
if event.Message != nil && !validSupportCaseText(*event.Message, maxSupportCasePublicTextRunes) {
return invalidSupportCase(location, "event message is invalid public text")
}
return validateSupportCaseEventShape(location, event)
}
func validateSupportCaseEventShape(location string, event SupportCaseEventSnapshot) error {
switch event.Kind {
case SupportCaseEventCreated:
return validateSupportCaseCreatedEvent(location, event)
case SupportCaseEventStatusChanged:
return validateSupportCaseStatusEvent(location, event)
case SupportCaseEventReply:
return validateSupportCaseReplyEvent(location, event)
case SupportCaseEventDecision:
return validateSupportCaseDecisionEvent(location, event)
}
return invalidSupportCase(location, "event kind is unknown")
}
func validateSupportCaseCreatedEvent(location string, event SupportCaseEventSnapshot) error {
if event.Actor != SupportCaseActorUser || event.Status == nil || *event.Status != SupportCaseStatusSubmitted || event.Message != nil {
return invalidSupportCase(location, "created event fields are invalid")
}
return nil
}
func validateSupportCaseStatusEvent(location string, event SupportCaseEventSnapshot) error {
if event.Actor == SupportCaseActorUser || event.Status == nil {
return invalidSupportCase(location, "status event fields are invalid")
}
return nil
}
func validateSupportCaseReplyEvent(location string, event SupportCaseEventSnapshot) error {
if event.Status != nil || event.Message == nil {
return invalidSupportCase(location, "reply event requires public text and no status")
}
return nil
}
func validateSupportCaseDecisionEvent(location string, event SupportCaseEventSnapshot) error {
if event.Actor != SupportCaseActorSupport || event.Status == nil || *event.Status != SupportCaseStatusResolved || event.Message == nil {
return invalidSupportCase(location, "decision event fields are invalid")
}
return nil
}
func supportObjectAllowed(caseType SupportCaseType, objectType SupportCaseObjectType) bool {
switch caseType {
case SupportCaseTypeSupport:
return objectType.IsKnown()
case SupportCaseTypeComplaint:
return objectType == SupportCaseObjectOrganization || objectType == SupportCaseObjectInvitation
case SupportCaseTypeGradeAppeal:
return objectType == SupportCaseObjectAssessmentAttempt || objectType == SupportCaseObjectSupportCase
case SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment:
return objectType == SupportCaseObjectAssessmentAttempt
default:
return false
}
}
func supportDecisionAllowed(caseType SupportCaseType, outcome SupportCaseDecisionOutcome) bool {
switch caseType {
case SupportCaseTypeSupport:
return outcome == SupportCaseDecisionAnswered
case SupportCaseTypeManualAssessment:
return outcome == SupportCaseDecisionAssessed
case SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal:
return outcome == SupportCaseDecisionUpheld || outcome == SupportCaseDecisionPartiallyUpheld ||
outcome == SupportCaseDecisionNotUpheld
default:
return false
}
}
func requiresInvitation(reason *SupportCaseComplaintReason) bool {
return reason != nil && (*reason == SupportComplaintOfferContent || *reason == SupportComplaintSalaryTermsViolation)
}
func validSupportCaseDescription(value string) bool {
if !utf8.ValidString(value) || strings.ContainsRune(value, 0) || utf8.RuneCountInString(value) < 1 ||
utf8.RuneCountInString(value) > maxSupportCaseDescriptionRunes {
return false
}
return strings.ContainsFunc(value, func(character rune) bool { return !unicode.IsSpace(character) && character != '\uFEFF' })
}
func validSupportCaseText(value string, maximumRunes int) bool {
return utf8.ValidString(value) && !strings.ContainsRune(value, 0) && utf8.RuneCountInString(value) >= 1 &&
utf8.RuneCountInString(value) <= maximumRunes
}
func invalidSupportCase(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidSupportCase)
}
func cloneSupportCaseSnapshot(snapshot SupportCaseSnapshot) SupportCaseSnapshot {
cloned := snapshot
cloned.CreatedAt = canonicalSupportTime(snapshot.CreatedAt)
cloned.UpdatedAt = canonicalSupportTime(snapshot.UpdatedAt)
cloned.Object = cloneSupportCaseReference(snapshot.Object)
cloned.AssessmentTarget = cloneSupportCaseAssessmentTarget(snapshot.AssessmentTarget)
cloned.ComplaintReason = cloneComplaintReason(snapshot.ComplaintReason)
cloned.RubricVersion = cloneInt32Pointer(snapshot.RubricVersion)
cloned.RubricOpeningID = cloneUUIDPointer(snapshot.RubricOpeningID)
cloned.RubricPolicyID = clonePolicyVersionIDPointer(snapshot.RubricPolicyID)
cloned.ResponseTarget = cloneSupportResponseTargetSnapshot(snapshot.ResponseTarget)
if snapshot.Decision != nil {
decision := *snapshot.Decision
decision.DecidedAt = canonicalSupportTime(decision.DecidedAt)
cloned.Decision = &decision
}
cloned.History = make([]SupportCaseEventSnapshot, len(snapshot.History))
for index, event := range snapshot.History {
cloned.History[index] = cloneSupportCaseEventSnapshot(event)
}
return cloned
}
func cloneSupportCaseSummary(summary SupportCaseSummary) SupportCaseSummary {
cloned := summary
cloned.Object = cloneSupportCaseReference(summary.Object)
cloned.AssessmentTarget = cloneSupportCaseAssessmentTarget(summary.AssessmentTarget)
cloned.ResponseTarget = cloneSupportResponseTargetSnapshot(summary.ResponseTarget)
if summary.DecisionOutcome != nil {
outcome := *summary.DecisionOutcome
cloned.DecisionOutcome = &outcome
}
return cloned
}
func cloneSupportCaseEventSnapshot(snapshot SupportCaseEventSnapshot) SupportCaseEventSnapshot {
cloned := snapshot
cloned.OccurredAt = canonicalSupportTime(snapshot.OccurredAt)
if snapshot.Status != nil {
status := *snapshot.Status
cloned.Status = &status
}
if snapshot.Message != nil {
message := *snapshot.Message
cloned.Message = &message
}
return cloned
}
func cloneSupportCaseCreateOutcomeSnapshot(snapshot SupportCaseCreateOutcomeSnapshot) SupportCaseCreateOutcomeSnapshot {
cloned := snapshot
if snapshot.Case != nil {
caseSnapshot := cloneSupportCaseSnapshot(*snapshot.Case)
cloned.Case = &caseSnapshot
}
return cloned
}
func cloneSupportResponseTargetSnapshot(snapshot SupportResponseTargetSnapshot) SupportResponseTargetSnapshot {
cloned := snapshot
cloned.DueAt = canonicalSupportTime(snapshot.DueAt)
cloned.AnsweredAt = canonicalSupportTimePointer(snapshot.AnsweredAt)
return cloned
}
func cloneSupportCaseReference(value *SupportCaseReference) *SupportCaseReference {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func cloneSupportCaseAssessmentTarget(value *SupportCaseAssessmentTarget) *SupportCaseAssessmentTarget {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func cloneComplaintReason(value *SupportCaseComplaintReason) *SupportCaseComplaintReason {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func supportCaseStatusPointer(value SupportCaseStatus) *SupportCaseStatus { return &value }
func supportCaseDecisionOutcomePointer(value SupportCaseDecisionOutcome) *SupportCaseDecisionOutcome {
return &value
}
func cloneInt32Pointer(value *int32) *int32 {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func cloneUUIDPointer(value *uuid.UUID) *uuid.UUID {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func clonePolicyVersionIDPointer(value *PolicyVersionID) *PolicyVersionID {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
func cloneTimePointer(value *time.Time) *time.Time {
if value == nil {
return nil
}
cloned := canonicalSupportTime(*value)
return &cloned
}
func canonicalSupportTime(value time.Time) time.Time {
return value.UTC().Truncate(time.Microsecond)
}
func canonicalSupportTimePointer(value *time.Time) *time.Time {
if value == nil {
return nil
}
cloned := canonicalSupportTime(*value)
return &cloned
}