Skip to content

types ​

go
import "github.com/prescriptoo/prescriptoo-api/pkg/types"

Package types provides shared domain models, value objects, and service contracts.

Index ​

Variables ​

go
var (
    // ErrDoctorOrganizationInvalidInput indicates an invalid list limit or cursor.
    ErrDoctorOrganizationInvalidInput = errors.New("invalid doctor organization query")
    // ErrDoctorOrganizationUnavailable indicates a missing organization capability.
    ErrDoctorOrganizationUnavailable = errors.New("doctor organization service unavailable")
)

go
var (
    // ErrPatientInvalidInput rejects invalid patient data.
    ErrPatientInvalidInput = errors.New("invalid patient input")
    // ErrPatientUnauthorized indicates that current patient authentication failed.
    ErrPatientUnauthorized = errors.New("patient authentication required")
    // ErrPatientForbidden indicates missing patient authority.
    ErrPatientForbidden = errors.New("patient access forbidden")
    // ErrPatientNotFound hides absent or inaccessible patient resources.
    ErrPatientNotFound = errors.New("patient not found")
    // ErrPatientConflict indicates a stale version or conflicting retry.
    ErrPatientConflict = errors.New("patient version or request conflict")
    // ErrPatientUnavailable indicates a required patient provider failure.
    ErrPatientUnavailable = errors.New("patient dependency unavailable")
)

go
var (
    // ErrInvalidEmail indicates that an email address has an invalid format.
    ErrInvalidEmail = errors.New("invalid email address")
    // ErrEmptyEmail indicates that an email address is empty.
    ErrEmptyEmail = errors.New("email address is empty")
    // ErrEmptyID indicates that an identifier is empty.
    ErrEmptyID = errors.New("id is empty")
)

func NormalizePatientEmail ​

go
func NormalizePatientEmail(s string) (string, string, error)

NormalizePatientEmail preserves display spelling and applies Identity-compatible comparison normalization.

func NormalizePatientPhone ​

go
func NormalizePatientPhone(s, region string) (string, string, error)

NormalizePatientPhone validates libphonenumber metadata and produces E.164.

func PatientFingerprint ​

go
func PatientFingerprint(x *PatientProfile) string

PatientFingerprint hashes normalized create intent without retaining another demographic payload.

func PatientMRN ​

go
func PatientMRN(n int64) string

PatientMRN formats a monotonically allocated organization-local number.

func PatientText ​

go
func PatientText(s string, maximum int) bool

PatientText validates bounded, nonblank Unicode text without control characters.

func ValidPatientID ​

go
func ValidPatientID(s string) bool

ValidPatientID accepts canonical nonzero UUIDs.

func ValidPatientKey ​

go
func ValidPatientKey(s string) bool

ValidPatientKey validates printable nonblank create retry keys.

func ValidatePatientPatch ​

go
func ValidatePatientPatch(in PatchPatientParams) error

ValidatePatientPatch rejects invalid presence, nonnullable values and server-owned fields.

type AdminHasPermissionInput ​

AdminHasPermissionInput requests a permission check for a verified platform administrator. Access defaults to AccessAny when omitted.

go
type AdminHasPermissionInput struct {
    UserID     ID
    Permission PermissionKey
    Access     ResourceAccess
}

type AdminPrincipal ​

AdminPrincipal defines a shared domain model.

go
type AdminPrincipal struct {
    AdminUserID string
    UserID      string
}

type AdminUser ​

AdminUser defines a shared domain model.

go
type AdminUser struct {
    ID             string
    UserID         string
    Status         string
    Name           string
    Email          string
    IdentityStatus string
    EmailVerified  bool
    CreatedAt      time.Time
    UpdatedAt      time.Time
}

type AdminUserPage ​

AdminUserPage defines a shared domain model.

go
type AdminUserPage struct {
    Items      []AdminUser
    NextCursor string
}

type BillingFeatureOverrides ​

BillingFeatureOverrides contains per-subscription feature overrides.

go
type BillingFeatureOverrides map[string]any

type BillingFeatures ​

BillingFeatures contains offering capacities and feature flags.

go
type BillingFeatures map[string]any

type BillingInvoice ​

BillingInvoice defines a shared domain model.

go
type BillingInvoice struct {
    IsOverdue            bool
    ID                   string
    InvoiceNumber        string
    OrganizationID       string
    SubscriptionID       string
    Description          string
    AmountMinor          int64
    Currency             string
    PaidMinor            int64
    BalanceMinor         int64
    CoveredPeriodStart   time.Time
    CoveredPeriodEnd     time.Time
    InvoiceDate          time.Time
    DueDate              time.Time
    Notes                string
    Status               string
    IssuedAt             *time.Time
    PaidAt               *time.Time
    VoidedAt             *time.Time
    VoidReason           string
    CreatedByAdminUserID string
    UpdatedByAdminUserID string
    VoidedByAdminUserID  string
    CreatedAt            time.Time
    UpdatedAt            time.Time
}

type BillingPayment ​

BillingPayment defines a shared domain model.

go
type BillingPayment struct {
    ID                    string
    InvoiceID             string
    SubscriptionID        string
    OrganizationID        string
    AmountMinor           int64
    Currency              string
    PaidAt                time.Time
    Method                string
    Reference             string
    Notes                 string
    Status                string
    RecordedByAdminUserID string
    CreatedAt             time.Time
    VoidedAt              *time.Time
    VoidedByAdminUserID   string
    VoidReason            string
}

type BillingPlan ​

BillingPlan defines a shared domain model.

go
type BillingPlan struct {
    ID          string
    Name        string
    Slug        string
    Description string
    PriceMinor  int64
    Currency    string
    Interval    string
    Features    BillingFeatures
    IsPublic    bool
    IsActive    bool
    ArchivedAt  *time.Time
    CreatedAt   time.Time
    UpdatedAt   time.Time
}

type BillingSubscription ​

BillingSubscription defines a shared domain model.

go
type BillingSubscription struct {
    IsWritable         bool
    ReadOnlyReason     string
    ID                 string
    OrganizationID     string
    Plan               BillingPlan
    PriceMinor         int64
    Currency           string
    FeatureOverrides   BillingFeatureOverrides
    EffectiveFeatures  BillingFeatures
    Status             string
    CurrentPeriodStart time.Time
    CurrentPeriodEnd   time.Time
    TrialEndsAt        *time.Time
    CanceledAt         *time.Time
    DeletedAt          *time.Time
    CreatedAt          time.Time
    UpdatedAt          time.Time
}

type CreatePatientParams ​

CreatePatientParams requires organization context, name, age and sex.

go
type CreatePatientParams struct {
    Email          *string `json:"email,omitempty" nullable:"true" maxLength:"255"`
    OrganizationID string  `json:"organization_id" minLength:"1" pattern:"\\S" format:"uuid"`
    Name           string  `json:"name" minLength:"1" maxLength:"255" pattern:"\\S" example:"Patient name"`
    Demographics
}

type CursorPagination ​

CursorPagination describes lists whose backing store exposes continuation only. Counts are deliberately omitted when the query does not compute them.

go
type CursorPagination struct {
    NextCursor string `json:"next_cursor"`
}

type CursorResponse ​

CursorResponse places collection items and pagination at the top level.

go
type CursorResponse[T any] struct {
    Message    string           `json:"message"`
    StatusCode int              `json:"status_code"`
    Data       []T              `json:"data" nullable:"false"`
    Pagination CursorPagination `json:"pagination"`
}

func CursorSuccess ​

go
func CursorSuccess[T any](message string, items []T, nextCursor string) CursorResponse[T]

CursorSuccess constructs a page with a non-null items array.

type Demographics ​

Demographics contains required age and sex alongside optional profile attributes.

go
type Demographics struct {
    Age        string `json:"age" minLength:"1" pattern:"\\S" doc:"Free-text reported age; no numeric or unit format is required."`
    Sex        string `json:"sex" enum:"male,female,other,unknown"`
    Phone      string `json:"phone,omitempty" maxLength:"64"`
    BloodGroup string `json:"blood_group,omitempty" enum:"A+,A-,B+,B-,AB+,AB-,O+,O-"`
    Address    string `json:"address,omitempty" minLength:"1" maxLength:"1000" pattern:"\\S"`
}

type DoctorCreatePatientInput ​

DoctorCreatePatientInput contains a verified acting user and registration intent. UserID is supplied by the calling use case after shared identity verification.

go
type DoctorCreatePatientInput struct {
    UserID         string
    IdempotencyKey string
    Params         CreatePatientParams
}

type DoctorGetPatientInput ​

DoctorGetPatientInput identifies a patient and the verified acting user.

go
type DoctorGetPatientInput struct{ UserID, PatientID string }

type DoctorListPatientsInput ​

DoctorListPatientsInput selects an organization and a bounded patient search. UserID is supplied by the calling use case, never decoded from HTTP.

go
type DoctorListPatientsInput struct {
    UserID, OrganizationID, Query, Cursor string
    Limit                                 int
}

type DoctorOrganization ​

DoctorOrganization contains the organization details available to registered doctors.

go
type DoctorOrganization struct {
    ID          string
    Name        string
    Slug        string
    Description string
    Address     string
    Status      OrganizationStatus
}

type DoctorOrganizationAssignment ​

DoctorOrganizationAssignment is an active professional affiliation to an active organization. IDs come from Organization storage, not ordinary account membership or client input.

go
type DoctorOrganizationAssignment struct {
    ID           string
    DoctorID     string
    Organization DoctorOrganization
}

type DoctorOrganizationPage ​

DoctorOrganizationPage contains active organization summaries and their continuation.

go
type DoctorOrganizationPage struct {
    Items      []DoctorOrganization
    NextCursor string
}

type DoctorPatchPatientInput ​

DoctorPatchPatientInput carries versioned updates for the verified acting user.

go
type DoctorPatchPatientInput struct {
    UserID, PatientID string
    Params            PatchPatientParams
}

type DoctorVerification ​

DoctorVerification defines a shared domain model.

go
type DoctorVerification struct {
    ID              string
    DoctorID        string
    UserID          string
    DoctorName      string
    LicenseNumber   string
    Specialization  string
    Documents       []string
    Status          string
    ReviewedBy      *string
    ReviewedAt      *time.Time
    RejectionReason *string
    Notes           string
    CreatedAt       time.Time
    UpdatedAt       time.Time
}

type DoctorVerificationPage ​

DoctorVerificationPage defines a shared domain model.

go
type DoctorVerificationPage struct {
    Items      []DoctorVerification
    NextCursor string
}

type Email ​

Email is a value object representing a validated email address.

go
type Email string

func NewEmail ​

go
func NewEmail(s string) (Email, error)

NewEmail creates an Email from a string, returns error if invalid.

func (Email) Equals ​

go
func (e Email) Equals(other Email) bool

Equals checks if two Emails are equal.

func (Email) IsEmpty ​

go
func (e Email) IsEmpty() bool

IsEmpty checks if the Email is empty.

func (Email) String ​

go
func (e Email) String() string

String returns the string representation of the Email.

func (Email) Validate ​

go
func (e Email) Validate() error

Validate checks if the Email is valid.

type Empty ​

Empty is the domain result of an operation without response data.

go
type Empty struct{}

type Entity ​

Entity is a base struct for domain entities with common fields.

go
type Entity struct {
    ID        ID
    CreatedAt time.Time
    UpdatedAt time.Time
}

type IAuthorizationService ​

IAuthorizationService defines the shared platform and organization checks. Callers must authenticate first and stop on either a false result or an error. A normal denial returns false, nil; invalid input or dependency failures return an error. Permission checks must enforce current membership eligibility.

go
type IAuthorizationService interface {
    // AdminHasPermission checks platform grants. Any grants also match Own checks;
    // Own grants never match Any checks. Matching explicit denials override allows,
    // and missing grants deny access.
    AdminHasPermission(ctx context.Context, input AdminHasPermissionInput) (bool, error)

    // OrgHasPermission checks grants within OrganizationID, using the same access
    // and denial rules as AdminHasPermission. It must not fall back to admin grants.
    OrgHasPermission(ctx context.Context, input OrgHasPermissionInput) (bool, error)
}

type ID ​

ID is a value object representing a unique identifier.

go
type ID string

func NewID ​

go
func NewID() ID

NewID creates a new ID with a generated UUID.

func NewIDFromString ​

go
func NewIDFromString(s string) (ID, error)

NewIDFromString creates an ID from a string, returns error if invalid.

func (ID) Equals ​

go
func (id ID) Equals(other ID) bool

Equals checks if two IDs are equal.

func (ID) IsEmpty ​

go
func (id ID) IsEmpty() bool

IsEmpty checks if the ID is empty.

func (ID) String ​

go
func (id ID) String() string

String returns the string representation of the ID.

func (ID) Validate ​

go
func (id ID) Validate() error

Validate checks if the ID is a valid UUID.

func (ID) Value ​

go
func (id ID) Value() string

Value returns the underlying string value of the ID.

type IIdentityService ​

IIdentityService defines the shared identity-verification capability.

go
type IIdentityService interface {
    // Verify validates a complete Authorization header and its persistent session.
    // Invalid, expired, or revoked credentials must return an error.
    Verify(ctx context.Context, authorization string) (*Identity, error)
}

type Identity ​

Identity is the verified user and persistent session shared between services.

go
type Identity struct {
    UserID    ID
    SessionID ID
}

type IdentityAccount ​

IdentityAccount defines a shared domain model.

go
type IdentityAccount struct {
    ID            string
    Email         string
    Name          string
    Status        string
    EmailVerified bool
    CreatedAt     time.Time
    UpdatedAt     time.Time
}

type ListDoctorOrganizationsQuery ​

ListDoctorOrganizationsQuery selects a page of active organizations.

go
type ListDoctorOrganizationsQuery struct {
    Limit  int
    Cursor string
}

type MedicineBrand ​

MedicineBrand defines a shared domain model.

go
type MedicineBrand struct {
    MedicineMetadata
    Name           string
    ManufacturerID string
    GenericID      string
}

type MedicineDrug ​

MedicineDrug defines a shared domain model.

go
type MedicineDrug struct {
    Route, TherapeuticClassID, CatalogueVersion string
    Aliases, IngredientIDs                      []string
    QuickSigs                                   []MedicineQuickSig
    MedicineMetadata
    BrandID      string
    Form         string
    Strength     string
    Brand        MedicineSummary
    Generic      MedicineSummary
    Manufacturer MedicineSummary
}

type MedicineGeneric ​

MedicineGeneric defines a shared domain model.

go
type MedicineGeneric struct {
    MedicineMetadata
    Name string
}

type MedicineManufacturer ​

MedicineManufacturer defines a shared domain model.

go
type MedicineManufacturer struct {
    MedicineMetadata
    Name string
}

type MedicineMetadata ​

MedicineMetadata defines a shared domain model.

go
type MedicineMetadata struct {
    ID          string
    Status      string
    Description *string
    CreatedAt   time.Time
    UpdatedAt   time.Time
    DeletedAt   *time.Time
}

type MedicinePage ​

MedicinePage defines a shared domain model.

go
type MedicinePage[T any] struct {
    Items       []T
    NextCursor  string
    CurrentPage int
    PerPage     int
    TotalPages  int
    TotalItems  int
}

type MedicineQuickSig ​

MedicineQuickSig preserves a curated editable direction preset without patient-specific dose inference.

go
type MedicineQuickSig struct{ ID, Label, Dose, Frequency, Timing, MealRelation, Duration string }

type MedicineSummary ​

MedicineSummary defines a shared domain model.

go
type MedicineSummary struct {
    ID   string
    Name string
}

type OrgHasPermissionInput ​

OrgHasPermissionInput requests a permission check for a verified user within exactly one organization. Access defaults to AccessAny when omitted.

go
type OrgHasPermissionInput struct {
    UserID         ID
    OrganizationID ID
    Permission     PermissionKey
    Access         ResourceAccess
}

type Organization ​

Organization defines a shared domain model.

go
type Organization struct {
    Type        *string `json:"type"`
    ID          string
    Name        string
    Slug        string
    Description string
    Phone       string
    Email       string
    Address     string
    Status      OrganizationStatus
    CreatedAt   time.Time
    UpdatedAt   time.Time
}

type OrganizationMember ​

OrganizationMember defines a shared domain model.

go
type OrganizationMember struct {
    ID             string
    UserID         string
    OrganizationID string
    Role           OrganizationMemberRole
    Status         string
    JoinedAt       time.Time
    CreatedAt      time.Time
    UpdatedAt      time.Time
}

type OrganizationMemberRole ​

OrganizationMemberRole identifies a membership's organization role.

go
type OrganizationMemberRole string

OrganizationMemberRoleAdmin identifies an organization administrator.

go
const OrganizationMemberRoleAdmin OrganizationMemberRole = "admin"

type OrganizationPage ​

OrganizationPage defines a shared domain model.

go
type OrganizationPage struct {
    Items       []Organization
    NextCursor  string
    CurrentPage int
    PerPage     int
    TotalPages  int
    TotalItems  int
}

type OrganizationStatus ​

OrganizationStatus is the lifecycle state of an organization.

go
type OrganizationStatus string

Organization lifecycle states.

go
const (
    OrganizationStatusActive    OrganizationStatus = "active"
    OrganizationStatusSuspended OrganizationStatus = "suspended"
    OrganizationStatusDeleted   OrganizationStatus = "deleted"
)

type Page ​

Page defines a shared domain model.

go
type Page[T any] struct {
    Items      []T
    NextCursor string
}

type Pagination ​

Pagination is the collection response metadata used by management APIs.

go
type Pagination struct {
    NextCursor  string `json:"next_cursor"`
    CurrentPage int    `json:"current_page"`
    PerPage     int    `json:"per_page"`
    TotalPages  int    `json:"total_pages"`
    TotalItems  int    `json:"total_items"`
}

func CursorPage ​

go
func CursorPage[T any](items []T, limit int, cursor, scope string, key func(T) (time.Time, string)) ([]T, Pagination, error)

CursorPage sorts a request-local, already-filtered collection in place and returns a descending keyset page. key must provide a timestamp and stable unique ID; the ID breaks timestamp ties so records do not repeat between pages.

scope must include the resource scope and every active filter. Its fingerprint and the requested limit are carried in the cursor to reject reuse for a different query. The cursor is a continuation token, not an authorization mechanism; callers must authorize and scope items before invoking this helper.

type PatchPatientParams ​

PatchPatientParams preserves omitted fields and records explicit nulls for clearing optional attributes.

go
type PatchPatientParams struct {
    ExpectedVersion int64           `json:"expected_version" minimum:"1"`
    Email           *string         `json:"email,omitempty" nullable:"true" maxLength:"255"`
    Name            *string         `json:"name,omitempty" nullable:"false" minLength:"1" maxLength:"255" pattern:"\\S"`
    Age             *string         `json:"age,omitempty" nullable:"false" minLength:"1" pattern:"\\S" doc:"Free-text reported age; no numeric or unit format is required."`
    Sex             *string         `json:"sex,omitempty" nullable:"false" enum:"male,female,other,unknown"`
    Phone           *string         `json:"phone,omitempty" nullable:"true" maxLength:"64"`
    BloodGroup      *string         `json:"blood_group,omitempty" nullable:"true" enum:"A+,A-,B+,B-,AB+,AB-,O+,O-"`
    Address         *string         `json:"address,omitempty" nullable:"true" minLength:"1" maxLength:"1000" pattern:"\\S"`
    Supplied        map[string]bool `json:"-"`
}

func (*PatchPatientParams) UnmarshalJSON ​

go
func (p *PatchPatientParams) UnmarshalJSON(data []byte) error

UnmarshalJSON distinguishes omitted fields from explicit nulls for future patch application.

type Patient ​

Patient is an organization-scoped profile, independent of prescription encounters.

go
type Patient struct {
    ID             string  `json:"id" doc:"Server-generated patient identifier."`
    OrganizationID string  `json:"organization_id"`
    Email          *string `json:"email,omitempty" maxLength:"255"`
    Version        int64   `json:"version"`
    MRN            string  `json:"mrn" doc:"Server-generated medical record number within the organization."`
    Name           string  `json:"name"`
    Demographics
    AgeRecordedAt   *time.Time `json:"age_recorded_at,omitempty" doc:"When the reported age was recorded."`
    CreatedByUserID string     `json:"created_by_user_id"`
    CreatedAt       time.Time  `json:"created_at"`
    UpdatedAt       time.Time  `json:"updated_at"`
}

type PatientPage ​

PatientPage is a cursor page with totals for the complete filtered query.

go
type PatientPage struct {
    Items                                        []Patient
    NextCursor                                   string
    CurrentPage, PerPage, TotalPages, TotalItems int
}

type PatientProfile ​

PatientProfile is an organization-owned patient record with private canonical contact values.

go
type PatientProfile struct {
    Patient
    EmailNormalized, PhoneE164, UpdatedByUserID string
}

func ApplyPatientPatch ​

go
func ApplyPatientPatch(before *PatientProfile, in PatchPatientParams, now time.Time, region string) (*PatientProfile, bool, error)

ApplyPatientPatch preserves omissions, applies clearing and compares the expected profile version.

func NewPatientProfile ​

go
func NewPatientProfile(in CreatePatientParams, now time.Time, region string) (*PatientProfile, error)

NewPatientProfile validates and normalizes a client registration without allocating identifiers.

func (*PatientProfile) AuditFields ​

go
func (x *PatientProfile) AuditFields() map[string]any

AuditFields explicitly selects the demographic history schema; never reflect a profile.

func (*PatientProfile) Normalize ​

go
func (x *PatientProfile) Normalize(region string) error

Normalize validates patient business rules and canonicalizes contacts.

func (*PatientProfile) SearchText ​

go
func (x *PatientProfile) SearchText() string

SearchText selects the explicitly searchable patient fields.

type PermissionKey ​

PermissionKey identifies an application-defined resource/action permission.

go
type PermissionKey string

type ResourceAccess ​

ResourceAccess selects whether a permission check concerns an owned resource or any resource within the requested scope.

go
type ResourceAccess string

go
const (
    // AccessAny requests access without an ownership restriction.
    AccessAny ResourceAccess = "any"
    // AccessOwn requests access to a resource the verified user owns.
    AccessOwn ResourceAccess = "own"
)

type Snapshot ​

Snapshot preserves patient display data at prescription issuance.

go
type Snapshot struct {
    ID   string `json:"id"`
    MRN  string `json:"mrn"`
    Name string `json:"name"`
    Demographics
    AgeRecordedAt *time.Time `json:"age_recorded_at,omitempty"`
}

type SuccessResponse ​

SuccessResponse is the common JSON envelope for successful API operations. StatusCode must match the HTTP response status.

go
type SuccessResponse[T any] struct {
    Message    string `json:"message"`
    StatusCode int    `json:"status_code"`
    Data       T      `json:"data" nullable:"false"`
}

func Success ​

go
func Success[T any](message string, status int, data T) SuccessResponse[T]

Success constructs a response while preserving the resource's concrete schema.

func SuccessList ​

go
func SuccessList[T any](message string, status int, data []T) SuccessResponse[[]T]

SuccessList ensures an empty unpaginated collection is encoded as [], not null.

type TokenPair ​

TokenPair defines a shared domain model.

go
type TokenPair struct {
    AccessToken  string
    RefreshToken string
    TokenType    string
    ExpiresIn    int64
}

Generated by gomarkdoc

Documentation follows the source. Planned contracts are marked explicitly.