types
import "github.com/prescriptoo/prescriptoo-api/pkg/types"Package types provides shared domain models, value objects, and service contracts.
Index
- Variables
- func NormalizePatientEmail(s string) (string, string, error)
- func NormalizePatientPhone(s, region string) (string, string, error)
- func PatientFingerprint(x *PatientProfile) string
- func PatientMRN(n int64) string
- func PatientText(s string, maximum int) bool
- func ValidPatientID(s string) bool
- func ValidPatientKey(s string) bool
- func ValidatePatientPatch(in PatchPatientParams) error
- type AdminHasPermissionInput
- type AdminPrincipal
- type AdminUser
- type AdminUserPage
- type BillingFeatureOverrides
- type BillingFeatures
- type BillingInvoice
- type BillingPayment
- type BillingPlan
- type BillingSubscription
- type CreatePatientParams
- type CursorPagination
- type CursorResponse
- type Demographics
- type DoctorCreatePatientInput
- type DoctorGetPatientInput
- type DoctorListPatientsInput
- type DoctorOrganization
- type DoctorOrganizationAssignment
- type DoctorOrganizationPage
- type DoctorPatchPatientInput
- type DoctorVerification
- type DoctorVerificationPage
- type Email
- type Empty
- type Entity
- type IAuthorizationService
- type ID
- type IIdentityService
- type Identity
- type IdentityAccount
- type ListDoctorOrganizationsQuery
- type MedicineBrand
- type MedicineDrug
- type MedicineGeneric
- type MedicineManufacturer
- type MedicineMetadata
- type MedicinePage
- type MedicineQuickSig
- type MedicineSummary
- type OrgHasPermissionInput
- type Organization
- type OrganizationMember
- type OrganizationMemberRole
- type OrganizationPage
- type OrganizationStatus
- type Page
- type Pagination
- type PatchPatientParams
- type Patient
- type PatientPage
- type PatientProfile
- func ApplyPatientPatch(before *PatientProfile, in PatchPatientParams, now time.Time, region string) (*PatientProfile, bool, error)
- func NewPatientProfile(in CreatePatientParams, now time.Time, region string) (*PatientProfile, error)
- func (x *PatientProfile) AuditFields() map[string]any
- func (x *PatientProfile) Normalize(region string) error
- func (x *PatientProfile) SearchText() string
- type PermissionKey
- type ResourceAccess
- type Snapshot
- type SuccessResponse
- type TokenPair
Variables
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")
)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")
)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
func NormalizePatientEmail(s string) (string, string, error)NormalizePatientEmail preserves display spelling and applies Identity-compatible comparison normalization.
func NormalizePatientPhone
func NormalizePatientPhone(s, region string) (string, string, error)NormalizePatientPhone validates libphonenumber metadata and produces E.164.
func PatientFingerprint
func PatientFingerprint(x *PatientProfile) stringPatientFingerprint hashes normalized create intent without retaining another demographic payload.
func PatientMRN
func PatientMRN(n int64) stringPatientMRN formats a monotonically allocated organization-local number.
func PatientText
func PatientText(s string, maximum int) boolPatientText validates bounded, nonblank Unicode text without control characters.
func ValidPatientID
func ValidPatientID(s string) boolValidPatientID accepts canonical nonzero UUIDs.
func ValidPatientKey
func ValidPatientKey(s string) boolValidPatientKey validates printable nonblank create retry keys.
func ValidatePatientPatch
func ValidatePatientPatch(in PatchPatientParams) errorValidatePatientPatch 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.
type AdminHasPermissionInput struct {
UserID ID
Permission PermissionKey
Access ResourceAccess
}type AdminPrincipal
AdminPrincipal defines a shared domain model.
type AdminPrincipal struct {
AdminUserID string
UserID string
}type AdminUser
AdminUser defines a shared domain model.
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.
type AdminUserPage struct {
Items []AdminUser
NextCursor string
}type BillingFeatureOverrides
BillingFeatureOverrides contains per-subscription feature overrides.
type BillingFeatureOverrides map[string]anytype BillingFeatures
BillingFeatures contains offering capacities and feature flags.
type BillingFeatures map[string]anytype BillingInvoice
BillingInvoice defines a shared domain model.
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.
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.
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.
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.
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.
type CursorPagination struct {
NextCursor string `json:"next_cursor"`
}type CursorResponse
CursorResponse places collection items and pagination at the top level.
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
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.
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.
type DoctorCreatePatientInput struct {
UserID string
IdempotencyKey string
Params CreatePatientParams
}type DoctorGetPatientInput
DoctorGetPatientInput identifies a patient and the verified acting user.
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.
type DoctorListPatientsInput struct {
UserID, OrganizationID, Query, Cursor string
Limit int
}type DoctorOrganization
DoctorOrganization contains the organization details available to registered doctors.
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.
type DoctorOrganizationAssignment struct {
ID string
DoctorID string
Organization DoctorOrganization
}type DoctorOrganizationPage
DoctorOrganizationPage contains active organization summaries and their continuation.
type DoctorOrganizationPage struct {
Items []DoctorOrganization
NextCursor string
}type DoctorPatchPatientInput
DoctorPatchPatientInput carries versioned updates for the verified acting user.
type DoctorPatchPatientInput struct {
UserID, PatientID string
Params PatchPatientParams
}type DoctorVerification
DoctorVerification defines a shared domain model.
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.
type DoctorVerificationPage struct {
Items []DoctorVerification
NextCursor string
}type Email
Email is a value object representing a validated email address.
type Email stringfunc NewEmail
func NewEmail(s string) (Email, error)NewEmail creates an Email from a string, returns error if invalid.
func (Email) Equals
func (e Email) Equals(other Email) boolEquals checks if two Emails are equal.
func (Email) IsEmpty
func (e Email) IsEmpty() boolIsEmpty checks if the Email is empty.
func (Email) String
func (e Email) String() stringString returns the string representation of the Email.
func (Email) Validate
func (e Email) Validate() errorValidate checks if the Email is valid.
type Empty
Empty is the domain result of an operation without response data.
type Empty struct{}type Entity
Entity is a base struct for domain entities with common fields.
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.
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.
type ID stringfunc NewID
func NewID() IDNewID creates a new ID with a generated UUID.
func NewIDFromString
func NewIDFromString(s string) (ID, error)NewIDFromString creates an ID from a string, returns error if invalid.
func (ID) Equals
func (id ID) Equals(other ID) boolEquals checks if two IDs are equal.
func (ID) IsEmpty
func (id ID) IsEmpty() boolIsEmpty checks if the ID is empty.
func (ID) String
func (id ID) String() stringString returns the string representation of the ID.
func (ID) Validate
func (id ID) Validate() errorValidate checks if the ID is a valid UUID.
func (ID) Value
func (id ID) Value() stringValue returns the underlying string value of the ID.
type IIdentityService
IIdentityService defines the shared identity-verification capability.
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.
type Identity struct {
UserID ID
SessionID ID
}type IdentityAccount
IdentityAccount defines a shared domain model.
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.
type ListDoctorOrganizationsQuery struct {
Limit int
Cursor string
}type MedicineBrand
MedicineBrand defines a shared domain model.
type MedicineBrand struct {
MedicineMetadata
Name string
ManufacturerID string
GenericID string
}type MedicineDrug
MedicineDrug defines a shared domain model.
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.
type MedicineGeneric struct {
MedicineMetadata
Name string
}type MedicineManufacturer
MedicineManufacturer defines a shared domain model.
type MedicineManufacturer struct {
MedicineMetadata
Name string
}type MedicineMetadata
MedicineMetadata defines a shared domain model.
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.
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.
type MedicineQuickSig struct{ ID, Label, Dose, Frequency, Timing, MealRelation, Duration string }type MedicineSummary
MedicineSummary defines a shared domain model.
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.
type OrgHasPermissionInput struct {
UserID ID
OrganizationID ID
Permission PermissionKey
Access ResourceAccess
}type Organization
Organization defines a shared domain model.
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.
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.
type OrganizationMemberRole stringOrganizationMemberRoleAdmin identifies an organization administrator.
const OrganizationMemberRoleAdmin OrganizationMemberRole = "admin"type OrganizationPage
OrganizationPage defines a shared domain model.
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.
type OrganizationStatus stringOrganization lifecycle states.
const (
OrganizationStatusActive OrganizationStatus = "active"
OrganizationStatusSuspended OrganizationStatus = "suspended"
OrganizationStatusDeleted OrganizationStatus = "deleted"
)type Page
Page defines a shared domain model.
type Page[T any] struct {
Items []T
NextCursor string
}type Pagination
Pagination is the collection response metadata used by management APIs.
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
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.
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
func (p *PatchPatientParams) UnmarshalJSON(data []byte) errorUnmarshalJSON distinguishes omitted fields from explicit nulls for future patch application.
type Patient
Patient is an organization-scoped profile, independent of prescription encounters.
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.
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.
type PatientProfile struct {
Patient
EmailNormalized, PhoneE164, UpdatedByUserID string
}func ApplyPatientPatch
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
func NewPatientProfile(in CreatePatientParams, now time.Time, region string) (*PatientProfile, error)NewPatientProfile validates and normalizes a client registration without allocating identifiers.
func (*PatientProfile) AuditFields
func (x *PatientProfile) AuditFields() map[string]anyAuditFields explicitly selects the demographic history schema; never reflect a profile.
func (*PatientProfile) Normalize
func (x *PatientProfile) Normalize(region string) errorNormalize validates patient business rules and canonicalizes contacts.
func (*PatientProfile) SearchText
func (x *PatientProfile) SearchText() stringSearchText selects the explicitly searchable patient fields.
type PermissionKey
PermissionKey identifies an application-defined resource/action permission.
type PermissionKey stringtype ResourceAccess
ResourceAccess selects whether a permission check concerns an owned resource or any resource within the requested scope.
type ResourceAccess stringconst (
// 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.
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.
type SuccessResponse[T any] struct {
Message string `json:"message"`
StatusCode int `json:"status_code"`
Data T `json:"data" nullable:"false"`
}func Success
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
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.
type TokenPair struct {
AccessToken string
RefreshToken string
TokenType string
ExpiresIn int64
}Generated by gomarkdoc