User Flow Actions - martinmendozadev/StateForce GitHub Wiki

🚀 StateForce User Flow Actions

This page provides detailed diagrams for specific user actions within the StateForce platform. These actions represent critical workflows such as creating events, registering institutions, managing resources, handling patients, and more. Each diagram illustrates the steps involved, from user interaction to API calls and database updates, including happy paths and error scenarios, all aligned with the current database schema.

Core Concepts for Developers

Before diving into the specific action flows, it's important to understand the guiding principles derived from the operational context of StateForce and its Entity-Relationship Diagram (ERD):

🧑‍💻 Key Operational Concepts Based on Schema

  1. Central Coordination (CRUM Focus): Users with roles like Dispatcher or Manager (users.role), often operating within a coordination_center (a type of institution), are central to orchestrating emergency responses. Their actions drive event management (events table) and resource allocation (resources, event_resources).
  2. Comprehensive Patient Management: The system features dedicated tables for detailed patient tracking:
    • patients: Core patient information linked to an event_id.
    • patient_vitals: Time-series data for vital signs, recorded by a user_id.
    • patient_transfers: Manages the movement of patients between locations, involving events, institutions, resources, and users.
  3. Detailed Resource Management:
    • resources: Tracks individual resources, their status, available_units, total_units, and association with an institution_id and resource_type_id.
    • resource_types and resource_categories: Provide a hierarchical classification for resources.
  4. Institutional Hierarchy and Specialization:
    • institutions: Can have parent_institution_id for hierarchy and a director_in_charge_id.
    • medical_centers and base_rescues: Specialized institution types with specific attributes and relationships.
  5. User Roles, Skills, and Associations:
    • user_institutions: Links users to institutions with a specific role and position.
    • user_skills: Associates users with specialty_types, including proficiency and expiry.
    • user_callsigns: Manages user-specific callsigns within institutions.
  6. Granular Note-Taking and Attachments: The notes and attachments tables, along with numerous join tables (e.g., event_notes, patient_notes, resource_attachments), allow for contextual data attachment across various entities.
  7. Auditing and Location: The audit_logs table tracks all significant actions, while the locations table is central for geolocating all major entities.

1. 🏢 Registering a New Institution (Including Specialized Types)

Overview

Authorized users (Superadmin, Admin) register new institutions. This flow covers general institutions and specialized types like Medical Centers and Base Rescues, including their specific attributes and related records.

Detailed Description

This process is critical for building the network of available facilities. It uses a database transaction to ensure that when a specialized type like a Medical Center is created, both the base record in institutions and the specific record in medical_centers are created successfully, maintaining data integrity.

Actor: Superadmin or Admin Preconditions: User is authenticated and authorized. Access to "Institutions Management". Postconditions:

  • New record in institutions.
  • If applicable, new record in medical_centers or base_rescues.
  • Institution linked to a locations record.
  • audit_logs entry created for the action.

Workflow Diagram

flowchart TD
    A["Start: User accesses Institutions Management"] --> B["User clicks 'Add New Institution'"];
    B --> C["System displays 'Create Institution' form with type selector (General, Medical Center, Base Rescue)"];
    C --> D["User selects type and fills details (name, callsign, location, parent_id, director_id, type-specific fields)"];
    D --> E{"Client-Side Validation"};
    E -- Invalid --> F["UI: Highlight errors"];
    F --> D;
    E -- Valid --> G["User clicks 'Save'"];
    G --> H["API Call: POST /api/institutions with all data"];
    H --> I{"Backend: Authenticate & Authorize"};
    I -- Unauthorized --> I_Err["API 403 Forbidden"];
    I_Err --> I_Msg["UI: 'Permission Denied' alert"];
    I_Msg --> C;

    I -- Authorized --> J{"Backend: Validate General & Type-Specific Data (unique name/callsign, valid IDs)"};
    J -- Invalid --> K["API 422/400/409 (e.g., 'Callsign exists')"];
    K --> L["UI: Display specific errors on form"];
    L --> D;

    J -- Valid --> M["Backend: DB Transaction Start"];
    M --> N["Create 'institutions' record"];
    N --> O{Is it a Medical Center?};
    O -- Yes --> P["Create 'medical_centers' record"];
    P --> Q;
    O -- No --> O1{Is it a Base Rescue?};
    O1 -- Yes --> R["Create 'base_rescues' record"];
    R --> Q;
    O1 -- No --> Q;

    Q["Backend: Create 'audit_logs' entry"] --> S["Backend: DB Transaction Commit"];
    S -- Success --> T["API responds 201 Created"];
    T --> U["UI: 'Success' message, new institution appears in list"];
    U --> Z["End"];
    S -- DB Error --> S_Err["API 500 Internal Server Error"];
    S_Err --> S_Msg["UI: 'Unexpected error' alert"];
    S_Msg --> G;

2. 🚨 Creating a New Event

Overview

Dispatchers or Managers create new events based on incoming reports. This involves capturing essential details, location, priority, and an optional unique event_code.

Detailed Description

This is the starting point for any emergency response. The system must capture enough initial information to be actionable. The creation of an event with status pending triggers visibility on monitoring dashboards for command staff.

Actor: Dispatcher or Manager Preconditions: Authenticated and authorized. An external report (e.g., phone call) has been received. Postconditions:

  • A new events record is created.
  • The event becomes visible on the main operational dashboard.
  • An audit_logs entry is created.

Workflow Diagram

flowchart TD
    A["Start: Dispatcher receives report"] --> B["Navigates to Event Dashboard, clicks 'Create New Event'"];
    B --> C["System displays 'Create Event' form"];
    C --> D["Dispatcher fills details (type, location, priority, description, event_code, etc.)"];
    D --> E{"Client-Side Validation"};
    E -- Invalid --> F["UI: Highlight errors"];
    F --> D;
    E -- Valid --> G["User clicks 'Create Event'"];
    G --> H["API Call: POST /api/events"];
    H --> I{"Backend: Authenticate & Authorize"};
    I -- Unauthorized --> I_Err["API 403"];
    I_Err --> I_Msg["UI: 'Permission Denied' alert"];
    I_Msg --> C;

    I -- Authorized --> J{"Backend: Validate Data (location_id, enums, unique event_code if provided)"};
    J -- "Invalid (e.g., location not found, event_code duplicate)" --> K["API 422/400/409"];
    K --> L["UI: Display specific errors (e.g., 'Event Code already exists')"];
    L --> D;

    J -- Valid --> M["Backend: Create 'events' record"];
    M --> N["Backend: Create 'audit_logs' entry"];
    N -- Success --> O["API responds 201 Created"];
    O --> P["UI: 'Success', new event appears on dashboard/redirects to details page"];
    P --> Z["End"];
    N -- DB Error --> N_Err["API 500"];
    N_Err --> N_Msg["UI: 'Unexpected error' alert"];
    N_Msg --> G;

3. 🛠️ Managing Resources (Instance CRUD)

Overview

Admins or Managers manage the lifecycle of resource instances (e.g., a specific ambulance or a batch of medical kits). This flow focuses on the Create, Read, and Update operations for resource instances.

Detailed Description

This workflow is fundamental for maintaining an accurate inventory of available assets. It relies on pre-existing resource_types and resource_categories. The status and available_units fields are critical for the dispatch process.

Actor: Admin or Manager Preconditions: User is authenticated and authorized. resource_types and institutions exist. Postconditions: A record is created or updated in the resources table. An audit_logs entry is created.

Workflow Diagram

flowchart TD
    A["Start: User accesses Resource Management"] --> B{"Choose Action"};

    B -- "Create New Resource" --> C_New["User clicks 'Add New Resource'"];
    C_New --> C_Form["UI: Displays 'Create Resource' form (name, institution_id, resource_type_id, status, total_units, etc.)"];
    C_Form --> C_Fill["User fills form"];
    C_Fill --> C_Validate{"Client-Side Validation"};
    C_Validate -- Invalid --> C_Err_UI["UI: Highlight errors"];
    C_Err_UI --> C_Fill;
    C_Validate -- Valid --> C_Save["User clicks 'Save'"];
    C_Save --> C_API["API: POST /api/resources"];
    C_API --> C_Backend{"Backend: Auth, Validate (IDs exist, units logic), Create 'resources' record, Log audit"};
    C_Backend -- Success --> C_Success["API 201, UI: 'Success', resource added to list"];
    C_Success --> A;
    C_Backend -- "Validation Error" --> C_Err_Val["API 422/400"];
    C_Err_Val --> C_Msg_Val["UI: Specific error on form"];
    C_Msg_Val --> C_Fill;
    C_Backend -- "Server Error" --> C_Err_Server["API 500, UI: Generic error alert"];
    C_Err_Server --> C_Save;

    B -- "Update Existing Resource" --> U_Select["User selects resource, clicks 'Edit'"];
    U_Select --> U_Form["UI: Displays 'Edit Resource' form (pre-filled)"];
    U_Form --> U_Fill["User modifies form (e.g., updates status or available_units)"];
    U_Fill --> U_Save["User clicks 'Update'"];
    U_Save --> U_API["API: PUT /api/resources/{id}"];
    U_API --> U_Backend{"Backend: Auth, Validate, Update 'resources' record, Log audit"};
    U_Backend -- Success --> U_Success["API 200, UI: 'Success', list updated"];
    U_Success --> A;
    U_Backend -- "Error" --> U_Err_Server["API 4xx/500, UI: Error message"];
    U_Err_Server --> U_Form;

4. 🚒 Managing an Active Event (Assignments)

Overview

Dispatchers or Managers assign institutions (event_institutions) and resources (event_resources) to an active event. This includes specifying quantity_assigned for resources and noting the assigned_by_user_id.

Detailed Description

This is the core of the coordination process. The system must ensure that only available resources can be assigned and that all assignments are tracked. Updating resources.available_units is a critical step to prevent double-booking.

Actor: Dispatcher or Manager Preconditions: Event exists. User authenticated. Available institutions and resources exist. Postconditions: Records created in event_institutions or event_resources. resources.available_units is updated. audit_logs entries are created.

Workflow Diagram

flowchart TD
    A["Start: User on Event Detail page (Event ID: {id})"] --> B{"Choose Action"};

    B -- "Assign Institutions" --> B1_Init["User clicks 'Assign Institution'"];
    B1_Init --> B1_Select["UI: Select Institutions"];
    B1_Select --> B1_Confirm["User confirms"];
    B1_Confirm --> B1_APICall["API: POST /api/events/{id}/institutions"];
    B1_APICall --> B1_Backend{"Backend: Auth, Validate, Create 'event_institutions', Log audit"};
    B1_Backend -- Success --> B1_UIUpdate["UI: 'Success', list updated"];
    B1_UIUpdate --> B;
    B1_Backend -- "Error (e.g., already assigned)" --> B1_Error["API 4xx/500, UI: Error message"];
    B1_Error --> B1_Select;

    B -- "Assign Resources" --> B2_Init["User clicks 'Assign Resource'"];
    B2_Init --> B2_Select["UI: Select Resources & Specify 'quantity_assigned'"];
    B2_Select --> B2_Confirm["User confirms"];
    B2_Confirm --> B2_APICall["API: POST /api/events/{id}/resources"];
    B2_APICall --> B2_Backend{"Backend: Auth, Validate (quantity <= available_units), Create 'event_resources', Update 'resources.available_units', Log audit"};
    B2_Backend -- Success --> B2_UIUpdate["UI: 'Success', list updated, resource availability reflects change"];
    B2_UIUpdate --> B;
    B2_Backend -- "Error (e.g., insufficient units)" --> B2_Error["API 4xx/500, UI: Error message"];
    B2_Error --> B2_Select;

    B -- "Update Event Status" --> B3_Init["User clicks 'Update Status'"];
    B3_Init --> B3_Select["UI: Select new EventStatus"];
    B3_Select --> B3_Confirm["User confirms"];
    B3_Confirm --> B3_APICall["API: PUT /api/events/{id} with new status"];
    B3_APICall --> B3_Backend{"Backend: Auth, Validate, Update 'events.status', Log audit"};
    B3_Backend -- Success --> B3_UIUpdate["UI: 'Success', status updated"];
    B3_UIUpdate --> B;
    B3_Backend -- "Error" --> B3_Error["API 4xx/500, UI: Error message"];
    B3_Error --> B3_Select;

    B -- "View Details Only" --> Z["End / Continue Monitoring"];

5. 🚑 Registering a Patient to an Event

Overview

Field personnel or dispatchers register patients associated with an event, capturing basic demographic data and initial triage status.

Detailed Description

When individuals are identified at an event scene, their details are logged into the patients table, linked directly to the event_id. This is the first step in the patient care lifecycle within the system.

Actor: Paramedic, Dispatcher, Manager Preconditions: An active event exists. User is authenticated and authorized. Postconditions: A new record is created in the patients table. An audit_logs entry is created.

Workflow Diagram

flowchart TD
    A["Start: User on Event Detail page (Event ID: {id})"] --> B["User clicks 'Add Patient'"];
    B --> C["System displays 'Register Patient' form (name, age, gender, triage_status)"];
    C --> D["User fills patient details"];
    D --> E{"Client-Side Validation (e.g., age 0-125)"};
    E -- Invalid --> F["UI: Highlight errors on form"];
    F --> D;
    E -- Valid --> G["User clicks 'Save Patient'"];
    G --> H["API Call: POST /api/events/{id}/patients"];
    H --> I{"Backend: Authenticate & Authorize"};
    I -- Unauthorized --> I_Err["API 403"];
    I_Err --> I_Msg["UI: 'Permission Denied'"];
    I_Msg --> C;

    I -- Authorized --> J{"Backend: Validate Data (event_id exists, age range, enums)"};
    J -- Invalid --> K["API 422/400/404"];
    K --> L["UI: Displays specific errors on form"];
    L --> D;

    J -- Valid --> M["Backend: Create record in 'patients' table"];
    M --> N["Backend: Create record in 'audit_logs' table"];
    N -- Success --> O["API responds 201 Created"];
    O --> P["UI: 'Success! Patient registered.' Patient appears in event's patient list."];
    P --> A;
    N -- DB Error --> N_Err["API 500"];
    N_Err --> N_Msg["UI: 'Unexpected error' alert."];
    N_Msg --> G;

6. 🩺 Recording Patient Vitals

Overview

Authorized medical personnel record vital signs for a registered patient at various intervals. This creates a time-series history of the patient's condition.

Detailed Description

This workflow involves selecting a patient and submitting a set of vital signs which are stored in the patient_vitals table. The system automatically timestamps the entry (recorded_at) and links it to the logged-in user (recorded_by_user_id).

Actor: Paramedic, Nurse, Doctor Preconditions: A patient record exists. The user is authenticated and has medical permissions. Postconditions: A new record is created in the patient_vitals table. An audit_logs entry is created.

Workflow Diagram

flowchart TD
    A["Start: User on Patient Detail page (Patient ID: {pid})"] --> B["User clicks 'Record Vitals'"];
    B --> C["System displays 'Record Vitals' form (BP, HR, SpO2, etc.)"];
    C --> D["User enters vital signs data"];
    D --> E{"Client-Side Validation (e.g., numeric, within reasonable physiological ranges)"};
    E -- Invalid --> F["UI: Highlight errors"];
    F --> D;
    E -- Valid --> G["User clicks 'Save Vitals'"];
    G --> H["API Call: POST /api/patients/{pid}/vitals"];
    H --> I{"Backend: Authenticate & Authorize"};
    I -- Unauthorized --> I_Err["API 403"];
    I_Err --> I_Msg["UI: 'Permission Denied'"];
    I_Msg --> C;

    I -- Authorized --> J{"Backend: Validate Data (patient_id exists, data types/ranges)"};
    J -- Invalid --> K["API 422/400/404"];
    K --> L["UI: Displays specific errors"];
    L --> D;

    J -- Valid --> M["Backend: Create record in 'patient_vitals'"];
    M --> N["Backend: Create record in 'audit_logs' table"];
    N -- Success --> O["API responds 201 Created"];
    O --> P["UI: 'Success! Vitals recorded.' Vitals appear in patient's timeline."];
    P --> A;
    N -- DB Error --> N_Err["API 500"];
    N_Err --> N_Msg["UI: 'Unexpected error' alert."];
    N_Msg --> G;

7. 🚗 Requesting and Managing a Patient Transfer

Overview

This complex flow covers requesting a patient transfer, assigning transport, and tracking its status until arrival at a destination facility. It is a critical coordination function.

Detailed Description

A user initiates a transfer for a patient to a destination_institution using a transport_resource. The system tracks this process through the patient_transfers table, updating its status from pending to accepted, en_route, arrived, and finally done.

Actor: Dispatcher, Paramedic, Manager Preconditions: Patient is registered. Event is active. Destination and transport resources are identified. Postconditions:

  • A patient_transfers record is created and its status is updated throughout the lifecycle.
  • The status of the transport resource is updated.
  • Multiple audit_logs entries are created.

Workflow Diagram

flowchart TD
    subgraph RequestTransfer [Phase 1: Requesting Transfer]
        direction LR
        RT1["User on Patient/Event page, clicks 'Request Transfer' for Patient {pid}"] --> RT2["UI: Form (Destination Institution, Transport Resource)"];
        RT2 --> RT3["User selects Destination & Transport, clicks 'Submit Request'"];
        RT3 --> RT4["API: POST /api/patient-transfers"];
        RT4 --> RT5{"Backend: Auth, Validate (IDs, resource availability, institution capacity)"};
        RT5 -- Invalid --> RT5_Err["API 4xx, UI: Error (e.g., 'Transport unavailable')"];
        RT5_Err --> RT2;
        RT5 -- Valid --> RT6["Backend: Create 'patient_transfers' (status 'pending'), Log audit"];
        RT6 -- Success --> RT7["API 201, UI: 'Transfer Requested', Notify relevant parties"];
    end

    subgraph ManageTransfer [Phase 2: Managing Transfer 'e.g., by CRUM or Destination']
        direction LR
        MT1["User at CRUM/Destination views pending transfers"] --> MT2["Selects transfer, clicks 'Accept Transfer'"];
        MT2 --> MT3["API: PUT /api/patient-transfers/{id}/accept"];
        MT3 --> MT4{"Backend: Auth, Validate, Update 'patient_transfers.status' to 'accepted', Update 'resources.status', Log audit"};
        MT4 -- Success --> MT5["API 200, UI: 'Transfer Accepted'"];
        MT5 --> MT_UpdateLoop;

        MT_UpdateLoop["Ongoing: Update Transfer Status"];
        MT_UpdateLoop -- "Transport Departs" --> MT_Depart["Log 'departure_time', status 'en_route' via API"];
        MT_Depart --> MT_UpdateLoop;
        MT_UpdateLoop -- "Patient Arrives" --> MT_Arrive["Log 'arrival_time', status 'arrived' via API"];
        MT_Arrive --> MT_UpdateLoop;
        MT_UpdateLoop -- "Transfer Complete" --> MT_Done["Update status 'done' via API"];
        MT_Done --> Z_EndTransfer["End Transfer"];
        MT_UpdateLoop -- "Cancel Transfer" --> MT_Cancel["Update status 'cancelled' via API"];
        MT_Cancel --> Z_EndTransfer;
    end
    RT7 --> MT1;

8. 📧 Inviting and Onboarding a New User

Overview

Admins invite new users via email. The invitee uses a unique token to register and is automatically linked to an institution with a specified role and position.

Detailed Description

This flow secures the onboarding process. The invites table tracks the state of each invitation. Upon successful registration, the system creates the users record and the crucial link in user_institutions.

Actor: Admin/Superadmin (inviter), New User (invitee) Preconditions: Admin is authenticated and authorized. Postconditions: invites record is used. New users and user_institutions records are created. An audit_logs entry is created.

Workflow Diagram

flowchart TD
    subgraph Admin_Flow [Admin Sends Invitation]
        direction LR
        A1["Start: Admin in User Management"] --> A2["Clicks 'Invite New User'"];
        A2 --> A3["Fills form (email, institution_id, role, position)"];
        A3 --> A4["Clicks 'Send Invite'"];
        A4 --> A5["API: POST /api/invites"];
        A5 --> A6{"Backend: Auth, Validate, Gen Token, Create 'invites' record, Send Email, Log audit"};
        A6 -- Success --> A7["UI: Success message"];
        A6 -- "Error (e.g., email exists)" --> A8["API 4xx, UI: Error message"];
        A8 --> A3;
    end

    subgraph User_Flow [New User Accepts & Registers]
        direction LR
        U1["Invitee receives email, clicks token link"] --> U2["Registration page with token"];
        U2 --> U3["Fills form (name, password, etc.)"];
        U4["Clicks 'Create Account'"] --> U5["API: POST /api/users/register (form data & token)"];
        U3 --> U4;
        U5 --> U6{"Backend: Validate token (exists, not expired)"};
        U6 -- "Invalid Token" --> U6_Err["API 400/410, UI: 'Token invalid/expired'"];
        U6 -- "Valid Token" --> U7{"Backend: Validate input, Create 'users' record"};
        U7 --> U8{"Backend: Create 'user_institutions' record from invite data"};
        U8 --> U9["Backend: Update 'invites' record (status 'accepted'), Log audit"];
        U9 -- Success --> U10["API 201, UI: 'Success', User logged in, Redirect to dashboard"];
        U7 -- "Error creating user" --> U_Err_Create["API 422/500, UI: Error"];
        U_Err_Create --> U3;
    end
    A7 --> U1;

9. 👤 Managing User Roles and Skills

Overview

Admins manage user access by modifying their role and position within user_institutions. They also manage user_skills by linking users to specialty_types.

Detailed Description

This dual-purpose flow allows for granular control over user capabilities. Modifying a role in user_institutions changes permissions, while managing user_skills defines their operational qualifications.

Actor: Admin or Superadmin Preconditions: User exists. Admin is authenticated and authorized. Postconditions: Records in user_institutions or user_skills are updated/created/deleted. audit_logs entries are created.

Workflow Diagram

flowchart TD
    A["Start: Admin on User Profile page"] --> B{"Choose Action: Manage Roles/Positions OR Manage Skills"};

    B -- "Manage Roles/Positions" --> C1["Admin selects an institution link from 'user_institutions' list"];
    C1 --> C2["Clicks 'Edit Role/Position'"];
    C2 --> C3["UI: Form to change 'role' (enum) and 'position' (text)"];
    C3 --> C4["Admin makes changes, clicks 'Save'"];
    C4 --> C5["API: PUT /api/user-institutions/{user_id}/{institution_id}"];
    C5 --> C6{"Backend: Auth, Validate, Update 'user_institutions', Log audit"};
    C6 -- Success --> C7["API 200, UI: 'Success', profile updated"];
    C7 --> A;
    C6 -- "Error" --> C8["API 4xx/500, UI: Error message"];
    C8 --> C3;

    B -- "Manage Skills" --> D1["Admin clicks 'Add/Manage Skills'"];
    D1 --> D2["UI: Interface to add skills. User selects a 'specialty_type' from a list"];
    D2 --> D3["User sets 'skill_proficiency_level' and optional 'expiry_date'"];
    D3 --> D4["User clicks 'Add Skill'"];
    D4 --> D5["API: POST /api/user-skills with {user_id, skill_id, level, expiry_date}"];
    D5 --> D6{"Backend: Auth, Validate, Create 'user_skills' record, Log audit"};
    D6 -- Success --> D7["API 201, UI: 'Success', skill added to user's list"];
    D7 --> A;
    D6 -- "Error (e.g., skill already exists for user)" --> D8["API 409, UI: Error message"];
    D8 --> D2;

10. 💬 Logging a Communication Entry

Overview

This workflow models the process where a dispatcher logs a significant communication (like a radio call for support) related to an event, creating a permanent record.

Detailed Description

This is a key requirement for accountability and post-event analysis. Each entry in the communications_log is timestamped and linked to the event, the channel, and the user who logged it, providing a clear audit trail.

Actor: Dispatcher Preconditions: An active event is being managed. Postconditions: A new record is created in the communications_log table.

Workflow Diagram

flowchart TD
    A[Start] --> B{"A significant communication occurs (e.g., radio call)"};
    B --> C{Dispatcher on the Event Detail page clicks 'Log Communication'};
    C --> D[System displays the 'New Communication Log' form];
    subgraph D_Form [Log Details]
        D1[Channel: Selects 'Radio' from 'CommunicationChannel' enum]
        D2["From: Enters 'Ambulance A-08'"]
        D3[To: Enters 'CRUM Medical Director']
        D4["Summary: 'Ambulance requests advice...'"]
    end
    D --> E{User clicks 'Save Log'};
    E --> F["API Call: POST /api/communications-log with {event_id, ...log_data}"];
    F --> G{"Backend: Auth, Validate, Create 'communications_log' record"};
    G -->|Success| H[API responds 201 Created];
    H --> I[UI shows 'Success' toast and the new log entry appears in the event's activity feed];
    I --> C;
    G -->|Error| J["API responds with error. UI displays an alert."];
    J --> E;

    %% Cancellation
    D --> D_Cancel{User clicks 'Cancel'};
    D_Cancel --> Z_Cancel[Form closes without saving];
    Z_Cancel --> C;

11. 📝 Managing Notes (Generic)

Overview

Users create notes and can associate them with various entities like events (via event_notes), users (via user_notes), institutions (via institution_notes), patients (via patients_notes), etc. Notes have title, body, visibility, and a creator_user_id. note_editors tracks who edited a note.

Detailed Description

This flow focuses on creating a note and linking it to one primary entity. Viewing/editing notes would be similar.

Actor: Any authorized user Preconditions: User authenticated. Context entity (e.g., Event, Patient) exists. Postconditions: notes record created. Join table record (e.g., event_notes) created. audit_logs.

Key Steps

  1. User is viewing an entity (e.g., Event Detail page).
  2. User clicks "Add Note."
  3. UI: Form for notes (title, body, visibility). creator_user_id is current user.
  4. User fills form, clicks "Save Note."
  5. API Call: e.g., POST /api/events/{event_id}/notes (or generic /api/notes with entity link in payload).
  6. Backend:
    • Auth & Authorize.
    • Validate data.
    • DB Transaction:
      • Create notes record.
      • Create corresponding join table record (e.g., event_notes linking event_id and new note_id).
      • (Implicitly) note_editors might get an initial entry if creator is considered first editor.
      • Log in audit_logs.
  7. Response: Success (201), UI shows note. Error (4xx).

Workflow Diagram: Managing Notes

flowchart TD
    A["Start: User on an entity page (e.g., Event ID: {eid}, Patient ID: {pid})"] --> B["User clicks 'Add Note' to this entity"];
    B --> C["UI: Displays 'Create Note' form (title, body, visibility)"];
    C --> D["User fills note details"];
    D --> E{"Client-Side Validation"};
    E -- Invalid --> F["UI: Highlight errors"];
    F --> D;
    E -- Valid --> G["User clicks 'Save Note'"];
    G --> H["API Call: POST /api/{entity_type}/{entity_id}/notes (e.g., /api/events/{eid}/notes)"];
    H --> I["Backend: Authenticate & Authorize User for entity"];
    I -- Unauthorized --> I_Err["API 403, UI: Permission Denied"];
    I_Err --> C;

    I -- Authorized --> J{"Backend: Validate Note Data (title/body not empty, valid visibility)"};
    J -- Invalid --> K["API 422, UI: Specific errors on form"];
    K --> D;

    J -- Valid --> L["Backend: DB Transaction Start"];
    L --> M["Create 'notes' record (creator_user_id = current user)"];
    M --> N["Create join table record (e.g., 'event_notes' linking note_id to {eid})"];
    N --> O["(Optional) Create 'note_editors' record for creator"];
    O --> P["Create 'audit_logs' entry for note creation"];
    P --> Q["Backend: DB Transaction Commit"];
    Q -- Success --> R["API responds 201 Created"];
    R --> S["UI: Displays 'Success! Note added.' Note appears in entity's notes list."];
    S --> A;
    Q -- DB Error --> Q_Err["API 500, UI: Unexpected error saving note."];
    Q_Err --> G;

12. 💬 Logging Event-Specific Updates/Communications (Using Event Notes)

Overview

Dispatchers or field units log significant updates, decisions, or communications related to an active event. This uses the event_notes system, where a note is created and linked to the event_id.

Detailed Description

This is a specialized use of the "Managing Notes" flow, specifically for events. The note.body would contain the communication summary or update. note.title could be a timestamp or brief subject.

Actor: Dispatcher, Paramedic, Manager Preconditions: Active event. User authenticated. Postconditions: New notes record. New event_notes record. audit_logs.

Workflow Diagram: Logging Event-Specific Updates (via Event Notes)

flowchart TD
    A["Start: User on Event Detail page (Event ID: {eid}), communication/update occurs"] --> B["User clicks 'Log Update/Communication' (or 'Add Event Note')"];
    B --> C["UI: Displays 'New Event Note/Log' form (title - e.g., 'Radio Comms @10:30', body - details, visibility)"];
    C --> D["User fills log details"];
    D --> E{"Client-Side Validation"};
    E -- Invalid --> F["UI: Highlight errors"];
    F --> D;
    E -- Valid --> G["User clicks 'Save Log'"];
    G --> H["API Call: POST /api/events/{eid}/notes with note data"];
    H --> I["Backend: Authenticate & Authorize User for event"];
    I -- Unauthorized --> I_Err["API 403, UI: Permission Denied"];
    I_Err --> C;

    I -- Authorized --> J{"Backend: Validate Note Data"};
    J -- Invalid --> K["API 422, UI: Specific errors"];
    K --> D;

    J -- Valid --> L["Backend: DB Transaction Start"];
    L --> M["Create 'notes' record (creator_user_id = current user)"];
    M --> N["Create 'event_notes' record (linking note_id to {eid})"];
    N --> O["Create 'audit_logs' entry"];
    O --> P["Backend: DB Transaction Commit"];
    P -- Success --> Q["API responds 201 Created"];
    Q --> R["UI: Displays 'Log saved.' Update appears in event's timeline/notes."];
    R --> A;
    P -- DB Error --> P_Err["API 500, UI: Unexpected error."];
    P_Err --> G;

13. 📎 Attaching Files to Entities

Overview

Users upload files (attachments table) and associate them with various entities via join tables (e.g., event_attachments, institution_attachments, resource_attachments, medical_center_attachments, base_rescue_attachments).

Detailed Description

(Similar to previous, but acknowledging the various join tables based on context)

Workflow Diagram: Attach File

sequenceDiagram
    participant User
    participant UI
    participant API
    participant FileStorage
    participant DB

    User->>UI: On Entity Page (e.g., Event, Institution), Click 'Attach File'
    UI->>User: Display File Upload Dialog
    User->>UI: Select file, add description, visibility, Click 'Upload'
    
    UI->>API: POST /api/attachments (multipart/form-data with file, metadata, and entity_type, entity_id for linking)

    API->>DB: Authenticate & Authorize User for entity
    alt Auth Fails
        API->>UI: Respond 403 Forbidden
    end

    API->>FileStorage: Server-Side File Validation (type, size) & Store file
    alt File Validation/Storage Fails
        FileStorage-->>API: Error (e.g., too large, type not allowed, storage error)
        API->>UI: Respond 400/413/500
    else File OK
        FileStorage->>API: Return file_url
    end
    
    API->>DB: Validate metadata
    alt Metadata Invalid
        API->>UI: Respond 422
    end

    API->>DB: DB Transaction Start
    API->>DB: Create 'attachments' record (uploader_user_id, file_url, file_name, etc.)
    API->>DB: Based on entity_type, create join table record (e.g., 'event_attachments' linking event_id and new attachment_id)
    API->>DB: Log in 'audit_logs'
    
    alt DB Operation Fails
        API->>DB: Rollback Transaction
        API->>UI: Respond 500
    else Success
        DB->>API: Commit Transaction, Records created
        API->>UI: Success response (201 Created) with attachment details
        UI->>User: Display 'Success', Attachment listed
    end

14. 📅 Creating and Managing Calendar Entries

Overview

Authorized users schedule calendar_entries (meetings, training), linking them to institutions (via calendar_entries_institutions) and optionally to an event_id.

Detailed Description

(Similar to previous, ensuring calendar_entries_institutions is handled)

Workflow Diagram: Create Calendar Event

sequenceDiagram
    participant Manager
    participant UI
    participant API
    participant DB

    Manager->>UI: Navigate to Calendar, Click 'Create Calendar Entry'
    UI->>Manager: Display form (title, desc, scheduled_at, ends_at/duration, recurrence, priority, visibility, associated institution_ids, optional event_id)
    Manager->>UI: Fill form, Click 'Save'
    UI->>API: POST /api/calendar-entries with data

    API->>DB: Auth & Validate (data types, institution_ids exist, event_id exists if provided)
    alt Validation Fails
        API->>UI: Respond 4xx (e.g., 422, 400)
    end

    API->>DB: DB Transaction Start
    API->>DB: Create 'calendar_entries' record (creator_user_id, event_id if present)
    API->>DB: For each institution_id, create 'calendar_entries_institutions' record
    API->>DB: Log in 'audit_logs'
    
    alt DB Operation Fails
        API->>DB: Rollback
        API->>UI: Respond 500
    else Success
        DB->>API: Commit, Records created
        API->>UI: Success response (201 Created)
        UI->>Manager: Display 'Success', Entry on calendar
    end

15. 📜 Reviewing Audit Logs

Overview

Superadmins and Admins review audit_logs to track system actions. (This flow remains largely the same as it's about a generic logging table, but the entities being logged are now more diverse).

Detailed Description

(Same as previous)

Workflow Diagram: Reviewing Audit Logs

flowchart TD
    A["Start: Admin/Superadmin navigates to Audit Logs section"] --> B["UI: Displays recent audit logs (paginated)"];
    B --> C["User applies filters (entity_name, entity_id, action, user_id, date_range)"];
    C --> D["Clicks 'Apply Filters'"];
    D --> E["API: GET /api/audit-logs with filter params"];
    E --> F{"Backend: Auth, Validate Filters, Query 'audit_logs', Paginate"};
    F -- Success --> G["UI: Displays filtered, paginated audit logs"];
    F -- "Error (auth, invalid filter, server error)" --> H["API 4xx/500, UI: Error message"];
    G --> C;
    H --> C;
    G --> Z["End / View Log Details (old_value, new_value)"];

🛠 General Notes for All Flows

  • Real-Time Updates: Leverage real-time updates (e.g., WebSockets) for dynamic information like event status, resource availability, and patient tracking.
  • Error Handling: Robust API error handling with clear HTTP status codes and messages.
  • Data Privacy & Visibility: Enforce Visibility enums and role-based access control (RBAC) diligently at the backend.
  • Idempotency: Ensure critical operations are idempotent where appropriate.
  • API Versioning: Consider for long-term maintainability.
  • Transaction Management: Wrap related database operations in transactions to ensure atomicity.

Related Pages