Skip to content

User Flow Actions

Martin Mendoza edited this page Jun 10, 2025 · 6 revisions

πŸš€ 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, and handling patients. Each diagram illustrates the steps involved, from user interaction to API calls and database updates, including happy paths and error scenarios.

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

  1. Central Coordination (CRUM Focus): Users with roles such as Dispatcher or Manager, often operating within a coordination_center (a type of institution), are central to orchestrating emergency responses. Their actions drive event management and resource allocation.
  2. Patient-Centric Workflow: The system is designed to track a patient's journey comprehensively. Tables like patients (if it were present, or implied by event details), patient_vitals (if present), and patient_transfers (if present) would be pivotal. In the current schema, event details and resource assignments indirectly manage patient care.
  3. Communication Logging: The communications_log table is crucial for maintaining an auditable record of significant communications (e.g., radio, phone calls) related to events, ensuring transparency and accountability.
  4. Resource Management: The resources table, with its status and available_units fields, is key for dispatchers and managers making informed decisions about resource assignment during events.
  5. Institutional Hierarchy: Institutions (institutions table) can have parent-child relationships, allowing for structured organization of emergency services (e.g., a regional hospital overseeing smaller clinics or rescue bases).
  6. Role-Based Access Control (RBAC): User actions are governed by their assigned roles (users.role or user_institutions.role) and permissions, typically enforced by a system like Pundit.

1. 🏒 Registering a New Institution

Overview

Authorized users, such as Superadmins or Admins (with appropriate permissions for their scope), can add new institutions to the StateForce system. These institutions can include hospitals, rescue bases (base_rescues), medical centers (medical_centers), coordination centers, or other emergency-related facilities. This workflow ensures that institutions are properly registered, geolocated, and integrated into the system for resource management and operational coordination.

Detailed Description

This flow describes the step-by-step process for registering a new institution. It includes adding essential details (e.g., name, location, sector type, parent institution if applicable), handling data validations, processing the creation in the backend, and providing user feedback.

Actor: Superadmin or Admin Preconditions:

  1. User is authenticated and possesses the necessary authorization (e.g., superadmin role or admin role with privileges to manage institutions).
  2. User has access to the "Institutions Management" section or dashboard.

Postconditions:

  1. A new institution record is successfully created in the institutions table (and potentially medical_centers or base_rescues if it's a specialized type).
  2. The new institution is visible in relevant dashboards or lists.
  3. An entry is created in the audit_logs table recording the creation of the institution.

Key Steps in the Workflow

  1. Access Institutions Management: The user navigates to the "Institutions Management" section.
  2. Initiate New Institution Creation: The user clicks an "Add New Institution" (or similar) button.
  3. Display Registration Form: The system presents the "Create Institution" form. Key fields include:
    • name: Unique name for the institution.
    • callsign: Optional callsign.
    • sector_type: (e.g., public, private) from SectorType enum.
    • description: Textual description.
    • location_id: Selected via a map interface or by choosing an existing location from the locations table.
    • parent_institution_id: Optional, for hierarchical relationships (references institutions.id).
    • Specific fields if creating a medical_center or base_rescue (e.g., level, total_beds for medical centers).
  4. Fill Form Details: The user enters the required information. Client-side validation provides immediate feedback on format or missing required fields.
  5. Submit Form: The user clicks "Save" or "Create Institution."
  6. Client-Side Validation & UI Feedback: The system performs final client-side checks. A loading indicator may appear, and the submit button might be disabled to prevent multiple submissions.
  7. API Call: The frontend sends a POST request to an endpoint like /api/institutions with the form data.
  8. Backend Processing:
    • Authentication & Authorization: Verifies the user's identity and permissions.
    • Server-Side Validation: Validates data uniqueness (e.g., institutions.name), existence of foreign keys (e.g., location_id), and adherence to enum values.
    • Database Operations:
      • Creates a new record in the institutions table.
      • If applicable, creates related records (e.g., in medical_centers or base_rescues).
      • Creates an entry in the audit_logs table.
  9. Handle Backend Response:
    • Success (201 Created): The API returns a success response. The UI displays a success message (e.g., toast notification), closes the form, and updates the institutions list/dashboard.
    • Validation Error (422 Unprocessable Entity): The API returns error details. The UI displays specific error messages next to the problematic form fields.
    • Authorization Error (403 Forbidden): If permissions are insufficient.
    • Server Error (500 Internal Server Error): The UI displays a generic error message.
  10. Cancellation: The user can click "Cancel" at any point before final submission to discard changes and return to the previous view.

Workflow Diagram: Registering a New Institution

flowchart TD
    A["Start: User accesses Institutions Management"] --> B["User clicks 'Add New Institution'"];
    B --> C["System displays 'Create Institution' form"];

    C --> D["User fills in Institution Details (name, sector, location, etc.)"];
    D --> E{"Client-Side Validation"};
    E -- Invalid --> F["Highlight errors on form"];
    F --> D;
    E -- Valid --> G["User clicks 'Save'"];
    G --> H["Display loading spinner, disable 'Save' button"];

    H --> I["API Call: POST /api/institutions with form data"];
    I --> J["Backend: Authenticate & Authorize User"];
    J --> K{"Backend: Server-Side Validation (unique name, valid location, etc.)"};
    K -- Invalid --> L["API responds 422 Unprocessable Entity with error details"];
    L --> M["UI displays specific errors on form"];
    M --> D;
    K -- Valid --> N["Backend: Create record in 'institutions' table"];
    N --> O["Backend: Create related records (e.g., medical_centers) if applicable"];
    O --> P["Backend: Create record in 'audit_logs' table"];
    P --> Q["API responds 201 Created"];
    Q --> R["UI displays 'Success' notification, closes form"];
    R --> S["New Institution appears in Institutions Dashboard/List"];
    S --> Z["End"];

    J -- Unauthorized --> J_AuthFail["API responds 403 Forbidden"];
    J_AuthFail --> J_AuthMsg["UI displays 'Permission Denied' message"];
    J_AuthMsg --> C;

    P -- DB Error --> P_DBFail["API responds 500 Internal Server Error"];
    P_DBFail --> P_DBMsg["UI displays 'Unexpected error. Please try again.'"];
    P_DBMsg --> G;

    C --> Cancel["User clicks 'Cancel'"];
    Cancel --> A;
Loading

Additional Information for Developers

  • Transaction Management: Backend operations involving multiple table inserts (e.g., institutions and medical_centers) should be wrapped in a database transaction to ensure atomicity.
  • Location Handling: Consider allowing creation of a new locations record directly from the institution form if an existing one isn't suitable, or a robust search/selection mechanism for existing locations.
  • Specialized Institution Types: If creating a medical_center or base_rescue, the API endpoint might be more specific (e.g., /api/medical-centers) or the main /api/institutions endpoint might accept a type parameter to handle the creation of specialized records.

2. 🚨 Creating a New Event

Overview

Event creation is a fundamental workflow, typically performed by Dispatchers or Managers at a coordination center. It involves logging an incoming emergency report (e.g., from a phone call, radio transmission) into the StateForce system. This ensures emergencies are accurately recorded, geolocated, prioritized, and tracked for effective resource allocation and response coordination.

Detailed Description

This flow details the process of creating a new event, from receiving an external report to successfully logging it in the system. It covers data entry, validation, backend processing, and user feedback.

Actor: Dispatcher or Manager Preconditions:

  1. User is authenticated and authorized to create events.
  2. An external report of an incident has been received.

Postconditions:

  1. A new event record is created in the events table.
  2. The new event is visible on the "Event Dashboard" or relevant operational views.
  3. An entry is created in audit_logs.
  4. Optionally, an initial entry might be made in communications_log if the report itself is considered a significant communication.

Key Steps in the Workflow

  1. Receive External Report: Dispatcher receives information about an incident.
  2. Access Event Creation Interface: Dispatcher navigates to the "Event Dashboard" and clicks "Create New Event."
  3. Display Event Form: The system presents the "Create Event" form. Key fields include:
    • event_type: (e.g., medical_emergency, fire_incident) from EventCategory enum.
    • location_id: Selected via map or address input (linked to locations table).
    • reported_time: Defaults to now(), can be adjusted.
    • description: Detailed text about the incident.
    • priority_level: (e.g., critical, high) from PriorityLevel enum.
    • triage_status: Initial assessment (e.g., unknown, red) from TriageStatus enum.
    • people_affected: Estimated number.
    • reported_by_text: Free-text field for who reported the event.
  4. Fill Event Form: Dispatcher enters incident details. Client-side validation provides immediate feedback.
  5. Submit Event: Dispatcher clicks "Create Event" or "Save."
  6. Client-Side Validation & UI Feedback: Final client-side checks. Loading indicator may appear.
  7. API Call: Frontend sends POST /api/events with form data.
  8. Backend Processing:
    • Authentication & Authorization.
    • Server-Side Validation (e.g., valid location_id, enum values).
    • Database Operations:
      • Creates a new record in the events table.
      • Creates an entry in audit_logs.
      • (Optional) Creates an entry in communications_log.
  9. Handle Backend Response:
    • Success (201 Created): API returns success. UI shows success message, may redirect to the new event's detail page or update the event dashboard.
    • Validation Error (422 Unprocessable Entity): UI displays specific errors.
    • Server Error (500 Internal Server Error): UI displays generic error.
  10. Cancellation: User can cancel before final submission.

Workflow Diagram: Creating a New Event

flowchart TD
    A["Start: Dispatcher receives emergency report"] --> B["Dispatcher navigates to Event Dashboard"];
    B --> C["User clicks 'Create New Event'"];
    C --> D["System displays 'Create Event' form"];

    D --> E["Dispatcher fills in event details (type, location, priority, description, etc.)"];
    E --> F{"Client-Side Validation"};
    F -- Invalid --> G["Highlight errors on form"];
    G --> E;
    F -- Valid --> H["User clicks 'Create Event'"];
    H --> I["Display loading spinner, disable 'Create Event' button"];

    I --> J["API Call: POST /api/events with form data"];
    J --> K["Backend: Authenticate & Authorize User"];
    K --> L{"Backend: Server-Side Validation (valid location, enums, etc.)"};
    L -- Invalid --> M["API responds 422 Unprocessable Entity with error details"];
    M --> N["UI displays specific errors on form"];
    N --> E;
    L -- Valid --> O["Backend: Create record in 'events' table"];
    O --> P["Backend: Create record in 'audit_logs' table"];
    P --> Q["Backend: (Optional) Create record in 'communications_log' table"];
    Q --> R["API responds 201 Created"];
    R --> S["UI displays 'Success' notification, redirects to Event Details or updates dashboard"];
    S --> T["New Event is visible"];
    T --> Z["End"];

    K -- Unauthorized --> K_AuthFail["API responds 403 Forbidden"];
    K_AuthFail --> K_AuthMsg["UI displays 'Permission Denied' message"];
    K_AuthMsg --> D;

    Q -- DB Error --> Q_DBFail["API responds 500 Internal Server Error"];
    Q_DBFail --> Q_DBMsg["UI displays 'Unexpected error. Please try again.'"];
    Q_DBMsg --> H;

    D --> Cancel["User clicks 'Cancel'"];
    Cancel --> B;
Loading

3. πŸš’ Managing an Active Event

Overview

Once an event is created, Dispatchers or Managers actively manage it. This involves assigning relevant institutions (e.g., hospitals for patient transport, fire stations for response), allocating resources (personnel, vehicles, equipment), and updating the event's status as it progresses (e.g., from pending to en_route, on_scene, resolved, closed).

Detailed Description

This workflow outlines the primary actions taken on an active event's detail page: assigning institutions, assigning resources, and updating event status.

Actor: Dispatcher or Manager Preconditions:

  1. An event exists in the system (e.g., status: 'pending' or status: 'active').
  2. User is authenticated and authorized to manage events.
  3. Available institutions and resources exist in the system.

Postconditions:

  1. Selected institutions are linked to the event via event_institutions.
  2. Selected resources are assigned to the event via event_resources, and their available_units and status in the resources table are updated.
  3. The event's status in the events table is updated.
  4. All actions are recorded in audit_logs.

Key Workflow Actions

A. Assigning Institutions to an Event

  1. Access Event Details: User is viewing the detail page of an active event.
  2. Initiate Institution Assignment: User clicks "Assign Institution."
  3. Select Institutions: UI presents a list/search/map to select one or more relevant institutions (from institutions table).
  4. Confirm Assignment: User confirms selections.
  5. API Call: POST /api/events/{event_id}/institutions with selected institution IDs.
  6. Backend Processing:
    • Validate event and institution IDs.
    • Create records in event_institutions.
    • Log in audit_logs.
  7. UI Feedback: Success message; assigned institutions list updates on event page.

B. Assigning Resources to an Event

  1. Access Event Details: User is viewing the event detail page.
  2. Initiate Resource Assignment: User clicks "Assign Resource."
  3. Select Resources: UI presents a list/search of available resources (from resources table), allowing selection and quantity specification.
  4. Confirm Assignment: User confirms.
  5. API Call: POST /api/events/{event_id}/resources with selected resource IDs and quantities.
  6. Backend Processing:
    • Validate event, resource IDs, and available quantity.
    • Create records in event_resources.
    • Update resources.available_units and resources.status (e.g., to assigned).
    • Log in audit_logs.
  7. UI Feedback: Success message; assigned resources list updates; resource availability reflects changes.

C. Updating Event Status

  1. Access Event Details: User is viewing the event detail page.
  2. Initiate Status Update: User clicks "Update Status" or selects a new status from a dropdown.
  3. Select New Status: User chooses a new status from the EventStatus enum (e.g., en_route, resolved).
  4. Confirm Update: User confirms.
  5. API Call: PUT /api/events/{event_id} or PATCH /api/events/{event_id}/status with the new status.
  6. Backend Processing:
    • Validate event ID and new status.
    • Update events.status (and events.ended_at if status is resolved or closed).
    • Log in audit_logs.
  7. UI Feedback: Success message; event status display updates.

Workflow Diagram: Managing an Active Event

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 (from 'institutions' table)"];
    B1_Select --> B1_Confirm["User confirms selection"];
    B1_Confirm --> B1_APICall["API: POST /api/events/{id}/institutions"];
    B1_APICall --> B1_Backend{"Backend: Validate, Create 'event_institutions', Log 'audit_logs'"};
    B1_Backend -- Success --> B1_UIUpdate["UI: Success, Update assigned institutions list"];
    B1_UIUpdate --> B;
    B1_Backend -- Error --> B1_Error["UI: Display error message"];
    B1_Error --> B1_Select;

    B -- "Assign Resources" --> B2_Init["User clicks 'Assign Resource'"];
    B2_Init --> B2_Select["UI: Select Resources & Quantity (from 'resources' table)"];
    B2_Select --> B2_Confirm["User confirms selection"];
    B2_Confirm --> B2_APICall["API: POST /api/events/{id}/resources"];
    B2_APICall --> B2_Backend{"Backend: Validate, Create 'event_resources', Update 'resources' (status, available_units), Log 'audit_logs'"};
    B2_Backend -- Success --> B2_UIUpdate["UI: Success, Update assigned resources list, Update resource availability"];
    B2_UIUpdate --> B;
    B2_Backend -- Error --> B2_Error["UI: Display error message (e.g., resource unavailable)"];
    B2_Error --> B2_Select;

    B -- "Update Event Status" --> B3_Init["User clicks 'Update Status' or selects new status"];
    B3_Init --> B3_Select["UI: Select new EventStatus (e.g., 'resolved')"];
    B3_Select --> B3_Confirm["User confirms selection"];
    B3_Confirm --> B3_APICall["API: PUT /api/events/{id} with new status"];
    B3_APICall --> B3_Backend{"Backend: Validate, Update 'events.status' (and 'ended_at'), Log 'audit_logs'"};
    B3_Backend -- Success --> B3_UIUpdate["UI: Success, Update event status display"];
    B3_UIUpdate --> B;
    B3_Backend -- Error --> B3_Error["UI: Display error message"];
    B3_Error --> B3_Select;

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

4. πŸ“§ Inviting and Onboarding a New User

Overview

This workflow details how an Admin (or Superadmin) invites a new user to join StateForce and how the invited user completes their onboarding. This process uses the invites table to manage invitations and ensures users are correctly associated with an institution and role upon registration.

Detailed Description

Part 1: Admin Sends Invitation

  1. Access User Management: Admin navigates to the user management section.
  2. Initiate Invitation: Admin clicks "Invite New User."
  3. Fill Invitation Form: Admin provides:
    • email: Email address of the invitee.
    • institution_id: The primary institution the user will belong to.
    • role: The role the user will have within that institution (from Role enum, e.g., standard, manager).
  4. Send Invite: Admin submits the form.
  5. API Call: POST /api/invites with invitation details.
  6. Backend Processing:
    • Validate data (e.g., email format, valid institution_id, valid role).
    • Generate a unique, expiring token.
    • Create a record in the invites table (status sent, token, expires_at, inviter_id, institution_id, role).
    • Send an email to the invitee with a registration link containing the token.
    • Log in audit_logs.
  7. UI Feedback: Admin sees a success message.

Part 2: New User Accepts Invitation & Registers

  1. Receive Email: Invitee receives the invitation email.
  2. Click Registration Link: Invitee clicks the link, which navigates to a registration page on StateForce, passing the token.
  3. Display Registration Form: The registration form may pre-fill the email. User needs to provide:
    • first_name
    • last_name
    • password (and confirmation)
  4. Submit Registration: User submits the form.
  5. API Call: POST /api/users/register (or similar) with registration details and the token.
  6. Backend Processing:
    • Validate the token from the invites table (exists, not expired, status sent).
    • Validate user input (password strength, etc.).
    • Create a new record in the users table (set confirmed to true).
    • Create a record in user_institutions linking the new user to the institution_id and role from the invites record.
    • Update the invites record (status accepted, used_at).
    • Log in audit_logs.
  7. UI Feedback: User sees a success message, is logged in, and redirected to their dashboard. If token is invalid/expired, an error message is shown.

Workflow Diagram: Inviting and Onboarding User

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)"];
        A3 --> A4["Clicks 'Send Invite'"];
        A4 --> A5["API: POST /api/invites"];
        A5 --> A6{"Backend: Validate, Gen Token, Create 'invites' record, Send Email, Log 'audit_logs'"};
        A6 -- Success --> A7["UI: Success message"];
        A6 -- Error --> A8["UI: Error message"];
    end

    subgraph User_Flow [New User Accepts & Registers]
        direction LR
        U1["Invitee receives email with token link"] --> U2["Clicks link, navigates to registration page with token"];
        U2 --> U3["Fills registration form (name, password)"];
        U3 --> U4["Clicks 'Create Account'"];
        U4 --> U5["API: POST /api/users/register with form data & token"];
        U5 --> U6{"Backend: Validate token, Validate input, Create 'users' record, Create 'user_institutions' record, Update 'invites' record, Log 'audit_logs'"};
        U6 -- Success --> U7["UI: Success, User logged in, Redirect to dashboard"];
        U6 -- Invalid Token/Error --> U8["UI: Error message (e.g., token expired)"];
    end

    A7 --> U1;
    A8 --> A3;
    U8 --> U2;
Loading

5. πŸ‘€ Managing User Roles and Permissions

Overview

Admins or Superadmins manage user access by assigning or modifying roles within specific institutions. This workflow focuses on changing an existing user's role for a particular institution they are already associated with.

Detailed Description

This flow describes how an administrator updates a user's role within one of their associated institutions.

Actor: Admin or Superadmin Preconditions:

  1. User is authenticated and authorized to manage user roles.
  2. The target user exists and is associated with the institution in question (record in user_institutions).

Postconditions:

  1. The user's role in the specified user_institutions record is updated.
  2. An entry is created in audit_logs.

Key Steps in the Workflow

  1. Access User Profile: Admin navigates to the target user's profile page, which lists their institutional associations and roles.
  2. Select Institution for Role Change: Admin identifies the specific user_institutions entry to modify.
  3. Initiate Role Edit: Admin clicks an "Edit Role" button for that specific institutional assignment.
  4. Choose New Role: A dropdown or selection list appears with available roles from the Role enum. Admin selects the new role.
  5. Confirm Change: Admin confirms the new role selection.
  6. API Call: PUT /api/user-institutions/{user_id}/{institution_id} (or similar, using the composite key or a dedicated ID if user_institutions has one) with the new role.
  7. Backend Processing:
    • Authentication & Authorization.
    • Validate that the user_institutions record exists.
    • Update the role field in the identified user_institutions record.
    • Create an entry in audit_logs (capturing old_value and new_value for the role).
  8. Handle Backend Response:
    • Success (200 OK): UI displays a success message and reflects the updated role on the user's profile.
    • Not Found (404 Not Found): If the user_institutions record doesn't exist.
    • Validation Error (422 Unprocessable Entity): If the new role is invalid.
    • Server Error (500 Internal Server Error): UI displays generic error.

Workflow Diagram: Managing User Roles

flowchart TD
    A["Start: Admin on User Profile page"] --> B["Admin views user's institutional assignments (user_institutions records)"];
    B --> C["Admin selects a specific institution assignment and clicks 'Edit Role'"];
    C --> D["UI: Displays role selection (dropdown with Role enum values)"];
    D --> E["Admin selects new role"];
    E --> F["Admin clicks 'Save Role' or 'Confirm'"];

    F --> G["API Call: PUT /api/user-institutions/{user_id}/{institution_id} with new role"];
    G --> H["Backend: Authenticate & Authorize Admin"];
    H --> I{"Backend: Validate 'user_institutions' record exists"};
    I -- Not Found --> J["API responds 404 Not Found"];
    J --> K["UI: Displays 'User not associated with this institution in this way' error"];
    K --> C;
    I -- Found --> L{"Backend: Validate new role"};
    L -- Invalid --> M["API responds 422 Unprocessable Entity"];
    M --> N["UI: Displays 'Invalid role selected' error"];
    N --> D;
    L -- Valid --> O["Backend: Update 'role' in 'user_institutions' table"];
    O --> P["Backend: Create record in 'audit_logs' (old_value, new_value)"];
    P --> Q["API responds 200 OK"];
    Q --> R["UI: Displays 'Success' notification, updates role display on profile"];
    R --> Z["End"];

    P -- DB Error --> P_DBFail["API responds 500 Internal Server Error"];
    P_DBFail --> P_DBMsg["UI: Displays 'Unexpected error. Please try again.'"];
    P_DBMsg --> F;
Loading

6. πŸ“ž Managing Contacts (Simplified from #7 in prompt as it was similar)

Overview

This workflow covers creating a generic contact record and then associating that contact with an institution, specifying the nature of the contact (e.g., primary, emergency).

Detailed Description

Part 1: Creating a Generic Contact

  1. Access Contacts Directory: User (Admin/Manager) navigates to the contacts management section.
  2. Initiate New Contact: User clicks "Create New Contact."
  3. Fill Contact Form: User enters:
    • name
    • email (unique)
    • radio_frequency (optional)
    • Associated phone numbers can be added in a subsequent step or integrated here.
  4. Submit Contact: User saves the form.
  5. API Call: POST /api/contacts.
  6. Backend Processing: Validate (unique email), create record in contacts, log in audit_logs.
  7. UI Feedback: Success message, new contact appears in directory.

Part 2: Linking Contact to an Institution

  1. Access Contact Profile or Institution Profile: User navigates to either the contact's detail page or the institution's detail page.
  2. Initiate Linking: User clicks "Link Contact to Institution" (from contact page) or "Add Institution Contact" (from institution page).
  3. Select Contact/Institution & Type:
    • If on contact page: Search/select institution, select contact_type (from ContactTypes enum).
    • If on institution page: Search/select contact, select contact_type.
  4. Confirm Link: User confirms.
  5. API Call: POST /api/institution-contacts (or similar, e.g., POST /api/institutions/{id}/contacts).
  6. Backend Processing: Validate IDs, create record in institution_contacts (using composite key: institution_id, contact_id, contact_type), log in audit_logs.
  7. UI Feedback: Success message, link is displayed.

Workflow Diagram: Managing Contacts

flowchart TD
    subgraph CreateContact [Part 1: Create Generic Contact]
        direction LR
        CC1["Start: User in Contacts Directory"] --> CC2["Clicks 'Create New Contact'"];
        CC2 --> CC3["Fills form (name, email, radio_freq)"];
        CC3 --> CC4["Clicks 'Save Contact'"];
        CC4 --> CC5["API: POST /api/contacts"];
        CC5 --> CC6{"Backend: Validate, Create 'contacts' record, Log 'audit_logs'"};
        CC6 -- Success --> CC7["UI: Success, Contact in directory"];
        CC6 -- Error --> CC8["UI: Error message"];
    end

    subgraph LinkContact [Part 2: Link Contact to Institution]
        direction LR
        LC1["User on Contact Profile or Institution Profile"] --> LC2["Clicks 'Link Contact/Add Institution Contact'"];
        LC2 --> LC3["UI: Select Contact/Institution & Contact Type (Primary, Emergency, etc.)"];
        LC3 --> LC4["User confirms selection"];
        LC4 --> LC5["API: POST /api/institution-contacts"];
        LC5 --> LC6{"Backend: Validate, Create 'institution_contacts' record, Log 'audit_logs'"};
        LC6 -- Success --> LC7["UI: Success, Link displayed"];
        LC6 -- Error --> LC8["UI: Error message (e.g., link already exists)"];
    end

    CC7 --> LC1;
    CC8 --> CC3;
    LC8 --> LC3;
Loading

7. πŸš‘ Registering and Transferring a Patient (Simplified from #8 in prompt, assuming patients table is not directly in schema but managed via event context)

Overview

This workflow describes how event-related "patient" information (managed as part of an event's details or through specialized notes/resources) is handled, from initial report at an event scene to their notional transfer to a medical facility. Since there isn't a dedicated patients table, this focuses on how events, resources (e.g., ambulances), and event_institutions (e.g., hospitals) interact.

Detailed Description

Part 1: Logging Patient Information within an Event

  • Actor: Paramedic (Standard User) or Dispatcher
  • Action: When an event is created or updated (events table), details about affected individuals are recorded in events.description, events.people_affected, and potentially in linked notes (via event_notes). The events.triage_status reflects the overall severity.

Part 2: "Transferring" a Patient (Assigning Transport Resource and Destination Institution)

  • Actor: Dispatcher or Manager
  • Action:
    1. Identify Need: Based on event details and patient information (in events.description or notes), a decision is made to "transfer" (i.e., transport) affected individuals.
    2. Assign Transport Resource: An available ambulance (resources table, type 'Ambulance') is assigned to the event via event_resources. Its status changes to assigned.
    3. Assign Destination Facility: A medical center (institutions table, type 'Medical Center') is assigned to the event as a destination via event_institutions.
    4. Update Event/Resource Status:
      • The ambulance's status (in resources) might be updated (e.g., en_route_to_hospital, then at_hospital, then available after drop-off).
      • The event's status (events.status) might be updated (e.g., patient_en_route, patient_arrived_at_facility).
      • Notes in event_notes would track the patient's movement and handoff.

Workflow Diagram: Patient Handling (Event-Centric)

flowchart TD
    A["Start: Event is active, patient information logged in event details/notes"] --> B["Dispatcher/Manager decides patient needs transport"];

    B --> C_AssignAmbulance["Assign Ambulance (Resource) to Event"];
    C_AssignAmbulance --> C_SelectAmb["UI: Select available Ambulance from 'resources'"];
    C_SelectAmb --> C_ConfirmAmb["User confirms"];
    C_ConfirmAmb --> C_APIAmb["API: POST /api/events/{id}/resources (for ambulance)"];
    C_APIAmb --> C_BackendAmb{"Backend: Create 'event_resources', Update ambulance 'resources.status' to 'assigned/en_route_hospital', Log 'audit_logs'"};
    C_BackendAmb -- Success --> C_UIAmb["UI: Ambulance assigned, status updated"];

    C_UIAmb --> D_AssignHospital["Assign Destination Hospital (Institution) to Event"];
    D_AssignHospital --> D_SelectHosp["UI: Select Medical Center from 'institutions'"];
    D_SelectHosp --> D_ConfirmHosp["User confirms"];
    D_ConfirmHosp --> D_APIHosp["API: POST /api/events/{id}/institutions (for hospital)"];
    D_APIHosp --> D_BackendHosp{"Backend: Create 'event_institutions', Log 'audit_logs'"};
    D_BackendHosp -- Success --> D_UIHosp["UI: Hospital assigned"];

    D_UIHosp --> E_TrackProgress["Track Progress via Event Status & Notes"];
    E_TrackProgress --> E_UpdateAmbStatus1["Field unit (Ambulance) updates status: 'Arrived at Hospital' (via API on 'resources' or event note)"];
    E_UpdateAmbStatus1 --> E_UpdateEventStatus["Dispatcher updates 'events.status' (e.g., 'patient_at_facility')"];
    E_UpdateEventStatus --> E_UpdateAmbStatus2["Ambulance becomes 'available' (update 'resources.status') after patient handoff"];
    E_UpdateAmbStatus2 --> Z["End of this 'transfer' phase"];

    C_BackendAmb -- Error --> C_ErrorAmb["UI: Error assigning ambulance"];
    D_BackendHosp -- Error --> D_ErrorHosp["UI: Error assigning hospital"];
Loading

This flow is adapted as there's no explicit patients, patient_vitals, or patient_transfers table in the provided schema. Patient management is inferred through event details, notes, and resource/institution assignments.


8. πŸ’¬ Logging a Communication Entry (Simplified from #9 in prompt)

Overview

Dispatchers at the CRUM log significant communications (radio, phone) related to an active event into the communications_log table for audit and reference.

Detailed Description

  1. Access Event: Dispatcher is on an active event's detail page.
  2. Initiate Log: Clicks "Log Communication."
  3. Fill Log Form:
    • channel: (e.g., radio, phone) - This field is not in communications_log but is good practice, could be in description.
    • from_text / to_text: Free text for sender/receiver. Schema has from_user_id, to_user_id, from_resource_id, to_resource_id - form should map to these or use text fields if entities are external.
    • summary: The content of the communication.
    • event_id: Automatically linked.
    • user_id: (Dispatcher logging it) automatically linked.
  4. Submit Log: Clicks "Save Log."
  5. API Call: POST /api/communications-log (or POST /api/events/{id}/communications).
  6. Backend Processing: Validate, create record in communications_log, link to event_id and user_id, log in audit_logs.
  7. UI Feedback: Success message, log appears in event's communication timeline.

Workflow Diagram: Logging Communication

flowchart TD
    A["Start: Dispatcher on Event Detail page, significant communication occurs"] --> B["Clicks 'Log Communication'"];
    B --> C["UI: Displays 'New Communication Log' form"];
    C --> D["Dispatcher fills form (channel, from, to, summary)"];
    D --> E["Clicks 'Save Log'"];
    E --> F["API: POST /api/communications-log"];
    F --> G{"Backend: Validate, Create 'communications_log' record (linked to event_id, user_id), Log 'audit_logs'"};
    G -- Success --> H["UI: Success, Log appears in event timeline"];
    G -- Error --> I["UI: Error message"];
    H --> A;
    I --> C;
Loading

9. πŸ“œ Reviewing Audit Logs (Simplified from #10 in prompt)

Overview

Superadmins and Admins review the audit_logs table to track actions performed within the system for accountability and security.

Detailed Description

  1. Access Audit Logs: User navigates to the "Audit Logs" section in System Administration.
  2. Default View: Shows recent logs, sortable and paginated.
  3. Apply Filters: User can filter by:
    • entity_name (e.g., events, users)
    • entity_id
    • action (from LogActions enum: created, updated, delete)
    • user_id (who performed the action)
    • Date Range (created_at of the log entry)
  4. Retrieve Logs: User applies filters.
  5. API Call: GET /api/audit-logs with filter parameters.
  6. Backend Processing: Query audit_logs table based on filters, with pagination.
  7. Display Results: UI updates with filtered, paginated logs. Each entry shows timestamp, user, action, entity, and a way to view old_value/new_value (e.g., a modal showing JSON diff).

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: Query 'audit_logs' table based on filters, paginate results"};
    F -- Success --> G["UI: Displays filtered, paginated audit logs"];
    F -- Error --> H["UI: Error message (e.g., invalid filter)"];
    G --> C;
    H --> C;
    G --> Z["End / View Log Details"];
Loading

10. πŸ“… Create Calendar Event (Simplified from #11 in prompt)

Overview

A Manager (or other authorized user) schedules a new calendar event (e.g., team meeting, training) for an institution or team using the calendar_entries table.

Detailed Description

  1. Access Calendar: Manager navigates to the calendar module.
  2. Initiate New Event: Clicks "Create Calendar Event."
  3. Fill Event Form:
    • title, description
    • scheduled_at, ends_at (or duration)
    • priority (from PriorityLevel enum)
    • visibility (from Visibility enum)
    • recurrence_rule, repeat_until (if recurring)
    • Link to event_id (optional, if calendar entry is for a specific emergency event)
    • Link to institution_id (via calendar_entries_institutions table)
  4. Submit Event: Clicks "Save Event."
  5. API Call: POST /api/calendar-entries.
  6. Backend Processing: Validate, create calendar_entries record, create calendar_entries_institutions record, log in audit_logs.
  7. UI Feedback: Success message, event appears on calendar.

Workflow Diagram: Create Calendar Event

sequenceDiagram
    participant Manager
    participant UI
    participant API
    participant DB

    Manager->>UI: Navigate to Calendar, Click 'Create Event'
    UI->>Manager: Display 'Create Calendar Event' form
    Manager->>UI: Fill form (title, date, institution, etc.), Click 'Save'
    UI->>API: POST /api/calendar-entries with event data
    API->>DB: Validate data
    DB->>API: Validation OK
    API->>DB: Create 'calendar_entries' record
    API->>DB: Create 'calendar_entries_institutions' record
    API->>DB: Log in 'audit_logs'
    DB->>API: Records created
    API->>UI: Success response (201 Created)
    UI->>Manager: Display 'Success', Event appears on calendar
Loading

11. πŸ“Ž Attach File (Simplified from #12 in prompt)

Overview

Users can upload files (images, documents) and associate them with entities like events, institutions, or resources using the attachments table and corresponding join tables (e.g., event_attachments).

Detailed Description

  1. Access Entity: User is viewing an entity's detail page (e.g., an event).
  2. Initiate File Upload: Clicks "Attach File."
  3. Select File & Metadata: User selects a file from their device and optionally adds description, visibility. file_type might be auto-detected or selected.
  4. Upload File: Clicks "Upload."
  5. API Call: POST /api/attachments (or POST /api/events/{id}/attachments). File is sent as multipart/form-data.
  6. Backend Processing:
    • Validate file (size, type).
    • Store file (e.g., S3, local disk) and get file_url.
    • Create attachments record (uploader_user_id, file_url, file_name, file_type, file_size, content_type, description, visibility).
    • Create record in the relevant join table (e.g., event_attachments linking event_id and new attachment_id).
    • Log in audit_logs.
  7. UI Feedback: Success message, attachment appears in entity's attachments list.

Workflow Diagram: Attach File

sequenceDiagram
    participant User
    participant UI
    participant API
    participant FileStorage
    participant DB

    User->>UI: On Entity Page, 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)
    API->>FileStorage: Store file
    FileStorage->>API: Return file_url / storage path
    API->>DB: Validate metadata
    DB->>API: Validation OK
    API->>DB: Create 'attachments' record (with file_url, uploader_id, etc.)
    API->>DB: Create join table record (e.g., 'event_attachments')
    API->>DB: Log in 'audit_logs'
    DB->>API: Records created
    API->>UI: Success response (201 Created) with attachment details
    UI->>User: Display 'Success', Attachment listed on entity page
Loading

πŸ›  General Notes for All Flows

  • Real-Time Updates: Where appropriate (especially for event and resource management), these flows should leverage real-time updates (e.g., via ActionCable and Turbo Streams) to ensure all relevant users see changes instantly.
  • Error Handling: Each API endpoint should robustly handle potential errors (validation, authorization, server errors) and return appropriate HTTP status codes and error messages to the client for user-friendly display.
  • Data Privacy & Visibility: The Visibility enum on tables like notes and attachments is critical. Backend logic must enforce these visibility rules based on the requesting user's role and institutional affiliations.
  • Idempotency: For operations that might be retried (e.g., due to network issues), consider idempotency mechanisms where applicable.
  • API Versioning: While not detailed here, for a production system, API versioning should be considered.

Related Pages

πŸ“š StateForce Wiki Sidebar

Welcome to the StateForce Wiki! Use this sidebar to navigate through the documentation.


🏠 Home


πŸ›  System Design


πŸ—„ Database


🎨 Design & Style


🚦 User Workflows


πŸ§ͺ Testing


πŸ“Ž Others

This sidebar provides quick access to all the documentation pages. For detailed information, click on the desired section.

Clone this wiki locally