Skip to content

API Reference

Complete reference for CareLog's service layer APIs.

Service Architecture

All services follow a consistent pattern with CRUD operations and additional business logic methods.

DatabaseService

Core service for JSON-based data persistence.

Constructor

python
DatabaseService(db_path: str = "data/data.json")

Parameters:

  • db_path: Path to JSON database file

Methods

get(key: str) -> Any

Retrieve data by key.

python
users = db_service.get("users")

update(key: str, value: Any) -> None

Update or create data by key.

python
db_service.update("users", {"user1": {...}})

get_user_by_role(role: str) -> List[Dict]

Get all users with specified role.

python
doctors = db_service.get_user_by_role("doctor")

get_name_by_user_id(user_id: str) -> Optional[str]

Get user's name by ID.

python
name = db_service.get_name_by_user_id("user123")

UserService

Manages user accounts and authentication.

Constructor

python
UserService(db_service: DatabaseService)

Methods

create(name, firstName, lastName, email, password, role, **kwargs) -> User

Create a new user account.

Parameters:

  • name (str): Full display name
  • firstName (str): User's first name
  • lastName (str): User's last name
  • email (str): Unique email address (login username)
  • password (str): Plain text password (will be hashed)
  • role (str): User role ('patient', 'doctor', 'nurse', 'hospitaladmin', 'family')
  • **kwargs: Additional fields (linkedPatients, etc.)

Returns: Created User object

Example:

python
user = user_service.create(
    name="John Doe",
    firstName="John",
    lastName="Doe",
    email="john@example.com",
    password="secure123",
    role="patient"
)

get_by_id(user_id: str) -> Optional[User]

Get user by ID.

python
user = user_service.get_by_id("user123")
if user:
    print(user.name)

get_by_email(email: str) -> Optional[User]

Get user by email address.

python
user = user_service.get_by_email("john@example.com")

authenticate(email: str, password: str) -> Optional[User]

Authenticate user with email and password.

python
user = user_service.authenticate("john@example.com", "password123")
if user:
    print("Login successful")

update(user_id: str, **kwargs) -> Optional[User]

Update user fields.

python
updated_user = user_service.update(
    "user123",
    name="John Smith",
    role="doctor"
)

delete(user_id: str) -> bool

Delete user account.

python
success = user_service.delete("user123")

list() -> List[User]

Get all users.

python
all_users = user_service.list()

HealthLogService

Manages daily patient health logs.

Constructor

python
HealthLogService(db_service: DatabaseService)

Methods

create(patientID, physicalStatus, emotionalStatus, symptoms, isSensitive=False) -> HealthLog

Create a new health log entry.

Parameters:

  • patientID (str): Patient's user ID
  • physicalStatus (List[str] or str): Physical symptoms/status
  • emotionalStatus (List[str] or str): Emotional state
  • symptoms (str): Detailed symptom description
  • isSensitive (bool): Whether to hide from family members

Returns: Created HealthLog object

Example:

python
log = health_log_service.create(
    patientID="patient123",
    physicalStatus=["fever", "fatigue"],
    emotionalStatus=["anxious"],
    symptoms="High fever and headache",
    isSensitive=False
)

get(log_id: str) -> Optional[HealthLog]

Get health log by ID.

update(log_id: str, **kwargs) -> Optional[HealthLog]

Update health log fields.

delete(log_id: str) -> bool

Delete health log.

list() -> List[HealthLog]

Get all health logs.

get_by_patient(patient_id: str) -> List[HealthLog]

Get all health logs for a specific patient.

python
patient_logs = health_log_service.get_by_patient("patient123")

get_non_sensitive_by_patient(patient_id: str) -> List[HealthLog]

Get only non-sensitive health logs for a patient (used for family member view).

python
family_viewable = health_log_service.get_non_sensitive_by_patient("patient123")

AppointmentService

Manages medical appointments.

Constructor

python
AppointmentService(db_service: DatabaseService)

Methods

create(patientID, reason, requestedDate, status="Pending", **kwargs) -> Appointment

Create appointment request.

Parameters:

  • patientID (str): Patient requesting appointment
  • reason (str): Reason for appointment
  • requestedDate (str): Requested date/time (ISO format)
  • status (str): Initial status (default: "Pending")
  • **kwargs: Additional fields (doctorID, notes, etc.)

Example:

python
appointment = appointment_service.create(
    patientID="patient123",
    reason="Annual checkup",
    requestedDate="2025-11-01T10:00:00",
    status="Pending"
)

assign_doctor(appointment_id: str, doctor_id: str) -> Optional[Appointment]

Assign a doctor to an appointment.

python
updated = appointment_service.assign_doctor("appt123", "doctor456")

update_status(appointment_id: str, status: str) -> Optional[Appointment]

Update appointment status.

Status values: "Pending", "Scheduled", "Completed", "Cancelled"

python
appointment_service.update_status("appt123", "Completed")

get_by_patient(patient_id: str) -> List[Appointment]

Get all appointments for a patient.

get_by_doctor(doctor_id: str) -> List[Appointment]

Get all appointments assigned to a doctor.

get_pending() -> List[Appointment]

Get all pending appointment requests.

python
pending = appointment_service.get_pending()

MedicalRecordService

Manages comprehensive patient medical records.

Constructor

python
MedicalRecordService(db_service: DatabaseService)

Methods

create(patientID, diagnoses=None, prescriptions=None, appointments=None) -> MedicalRecord

Create medical record.

Parameters:

  • patientID (str): Patient ID
  • diagnoses (List[str]): List of diagnosis IDs
  • prescriptions (List[str]): List of prescription IDs
  • appointments (List[str]): List of appointment IDs

get_by_patient(patient_id: str) -> Optional[MedicalRecord]

Get complete medical record for patient.

python
record = medical_record_service.get_by_patient("patient123")
if record:
    print(f"Diagnoses: {len(record.diagnoses)}")

add_diagnosis(patient_id: str, diagnosis_id: str) -> Optional[MedicalRecord]

Add diagnosis to patient's medical record.

python
medical_record_service.add_diagnosis("patient123", "diag456")

add_prescription(patient_id: str, prescription_id: str) -> Optional[MedicalRecord]

Add prescription to patient's medical record.

add_appointment(patient_id: str, appointment_id: str) -> Optional[MedicalRecord]

Add appointment to patient's medical record.


DiagnosisService

Manages medical diagnoses.

Constructor

python
DiagnosisService(db_service: DatabaseService)

Methods

create(diagnosisID, doctorID, patientID, condition, notes, dateDiagnosed) -> Diagnosis

Create new diagnosis.

Parameters:

  • diagnosisID (str): Unique diagnosis ID
  • doctorID (str): Diagnosing doctor's ID
  • patientID (str): Patient's ID
  • condition (str): Diagnosed condition/disease
  • notes (str): Diagnosis notes and recommendations
  • dateDiagnosed (str): Date of diagnosis (ISO format)

Example:

python
diagnosis = diagnosis_service.create(
    diagnosisID="diag123",
    doctorID="doctor456",
    patientID="patient789",
    condition="Type 2 Diabetes",
    notes="Patient needs lifestyle changes and medication",
    dateDiagnosed="2025-10-26"
)

get(diagnosis_id: str) -> Optional[Diagnosis]

Get diagnosis by ID.

get_by_patient(patient_id: str) -> List[Diagnosis]

Get all diagnoses for a patient.

python
patient_diagnoses = diagnosis_service.get_by_patient("patient123")

get_by_doctor(doctor_id: str) -> List[Diagnosis]

Get all diagnoses made by a doctor.


PrescriptionService

Manages medication prescriptions.

Constructor

python
PrescriptionService(db_service: DatabaseService)

Methods

create(prescriptionID, doctorID, patientID, medication, dosage, instruction, datePrescribed) -> Prescription

Create new prescription.

Parameters:

  • prescriptionID (str): Unique prescription ID
  • doctorID (str): Prescribing doctor's ID
  • patientID (str): Patient's ID
  • medication (str): Medication name
  • dosage (str): Dosage amount (e.g., "500mg")
  • instruction (str): Administration instructions
  • datePrescribed (str): Prescription date (ISO format)

Example:

python
prescription = prescription_service.create(
    prescriptionID="presc123",
    doctorID="doctor456",
    patientID="patient789",
    medication="Metformin",
    dosage="500mg",
    instruction="Take twice daily with meals",
    datePrescribed="2025-10-26"
)

get(prescription_id: str) -> Optional[Prescription]

Get prescription by ID.

get_by_patient(patient_id: str) -> List[Prescription]

Get all prescriptions for a patient.

get_active_prescriptions(patient_id: str) -> List[Prescription]

Get active/current prescriptions for a patient.


EmergencyCallService

Manages emergency care requests.

Constructor

python
EmergencyCallService(db_service: DatabaseService)

Methods

create(emergency_call: EmergencyCall) -> EmergencyCall

Create emergency call.

Parameters:

  • emergency_call (EmergencyCall): Emergency call object

Example:

python
from core.models.emergency_call import EmergencyCall
import datetime

call = EmergencyCall(
    callID="call123",
    patientID="patient456",
    timestamp=datetime.datetime.now().isoformat(),
    urgencyLevel="HIGH",
    isResolved=False,
    isEscalated=False
)
created = emergency_call_service.create(call)

get_unresolved() -> List[EmergencyCall]

Get all unresolved emergency calls.

python
pending_calls = emergency_call_service.get_unresolved()

get_by_patient(patient_id: str) -> List[EmergencyCall]

Get all emergency calls from a patient.

respond_to_call(call_id: str, responder_id: str) -> Optional[EmergencyCall]

Mark emergency call as resolved with responder.

python
emergency_call_service.respond_to_call("call123", "nurse456")

escalate_call(call_id: str) -> Optional[EmergencyCall]

Escalate emergency call to doctor.

python
emergency_call_service.escalate_call("call123")

get_escalated() -> List[EmergencyCall]

Get all escalated emergency calls.


NotificationService

Manages system notifications.

Constructor

python
NotificationService(db_service: DatabaseService)

Methods

create(notificationID, userID, message, timestamp, isRead="unread") -> Notification

Create notification.

Parameters:

  • notificationID (str): Unique notification ID
  • userID (str): Recipient user ID
  • message (str): Notification message
  • timestamp (str): Creation timestamp (ISO format)
  • isRead (str): Read status ("unread" or "read")

Example:

python
notification = notification_service.create(
    notificationID="notif123",
    userID="user456",
    message="Your appointment is confirmed",
    timestamp="2025-10-26T10:00:00",
    isRead="unread"
)

get_by_user(user_id: str) -> List[Notification]

Get all notifications for a user.

python
user_notifications = notification_service.get_by_user("user123")

get_unread(user_id: str) -> List[Notification]

Get unread notifications for a user.

mark_as_read(notification_id: str) -> Optional[Notification]

Mark notification as read.

python
notification_service.mark_as_read("notif123")

VisitRequestService

Manages family visit requests.

Constructor

python
VisitRequestService(db_service: DatabaseService)

Methods

create(patientID, familyMemberID, requestedDate, status) -> VisitRequest

Create visit request.

Parameters:

  • patientID (str): Patient being visited
  • familyMemberID (str): Requesting family member
  • requestedDate (str): Requested visit date/time
  • status (str): Request status ("Submitted", "Approved", "Denied")

Example:

python
visit = visit_request_service.create(
    patientID="patient123",
    familyMemberID="family456",
    requestedDate="2025-10-27T14:00:00",
    status="Submitted"
)

get_by_patient(patient_id: str) -> List[VisitRequest]

Get all visit requests for a patient.

get_by_family_member(family_id: str) -> List[VisitRequest]

Get all visit requests from a family member.

approve_request(request_id: str) -> Optional[VisitRequest]

Approve visit request.

python
visit_request_service.approve_request("visit123")

deny_request(request_id: str) -> Optional[VisitRequest]

Deny visit request.


AuditLogService

Manages system audit logs.

Constructor

python
AuditLogService(db_service: DatabaseService)

Methods

create(logID, userID, action, timestamp, details) -> AuditLog

Create audit log entry.

Parameters:

  • logID (str): Unique log ID
  • userID (str): User who performed action
  • action (str): Action performed
  • timestamp (str): Action timestamp (ISO format)
  • details (str): Detailed description

Example:

python
audit_log_service.create(
    logID="log123",
    userID="user456",
    action="LOGIN",
    timestamp="2025-10-26T10:00:00",
    details="User logged in successfully"
)

get_by_user(user_id: str) -> List[AuditLog]

Get all audit logs for a user.

get_by_action(action: str) -> List[AuditLog]

Get all audit logs of a specific action type.

list() -> List[AuditLog]

Get all audit logs.


FeedbackService

Manages user feedback.

Constructor

python
FeedbackService(db_service: DatabaseService)

Methods

create(userID, category, message, timestamp) -> Feedback

Create feedback entry.

Parameters:

  • userID (str): User submitting feedback
  • category (str): Feedback category
  • message (str): Feedback message
  • timestamp (str): Submission timestamp (ISO format)

Example:

python
feedback = feedback_service.create(
    userID="user123",
    category="Service Quality",
    message="Great experience with the nursing staff!",
    timestamp="2025-10-26T10:00:00"
)

get_by_user(user_id: str) -> List[Feedback]

Get all feedback from a user.

get_by_category(category: str) -> List[Feedback]

Get all feedback of a specific category.


Utility Functions

Authentication (core.utils.auth)

PasswordHash

Password hashing utility using Argon2.

python
from core.utils.auth import PasswordHash

hasher = PasswordHash()

# Hash password
hashed = hasher.hash("mypassword")

# Verify password
is_valid = hasher.verify("mypassword", hashed)  # Returns True

Time Formatting (core.utils.timeformat)

to_readable(iso_timestamp: str) -> str

Convert ISO timestamp to readable format.

python
from core.utils.timeformat import to_readable

readable = to_readable("2025-10-26T10:00:00")
# Returns: "October 26, 2025 10:00 AM"

time_ago(iso_timestamp: str) -> str

Convert ISO timestamp to relative time.

python
from core.utils.timeformat import time_ago

relative = time_ago("2025-10-26T10:00:00")
# Returns: "2 hours ago"

Error Handling

All service methods that return Optional[T] will return None if the requested item is not found. Always check for None before accessing attributes:

python
user = user_service.get_by_id("user123")
if user is not None:
    print(user.name)
else:
    print("User not found")

Next Steps