-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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):
-
Central Coordination (
CRUMFocus): Users with roles such asDispatcherorManager, often operating within acoordination_center(a type ofinstitution), are central to orchestrating emergency responses. Their actions drive event management and resource allocation. -
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), andpatient_transfers(if present) would be pivotal. In the current schema, event details and resource assignments indirectly manage patient care. -
Communication Logging: The
communications_logtable is crucial for maintaining an auditable record of significant communications (e.g., radio, phone calls) related to events, ensuring transparency and accountability. -
Resource Management: The
resourcestable, with itsstatusandavailable_unitsfields, is key for dispatchers and managers making informed decisions about resource assignment during events. -
Institutional Hierarchy: Institutions (
institutionstable) can have parent-child relationships, allowing for structured organization of emergency services (e.g., a regional hospital overseeing smaller clinics or rescue bases). -
Role-Based Access Control (RBAC): User actions are governed by their assigned roles (
users.roleoruser_institutions.role) and permissions, typically enforced by a system like Pundit.
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.
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:
- User is authenticated and possesses the necessary authorization (e.g.,
superadminrole oradminrole with privileges to manage institutions). - User has access to the "Institutions Management" section or dashboard.
Postconditions:
- A new institution record is successfully created in the
institutionstable (and potentiallymedical_centersorbase_rescuesif it's a specialized type). - The new institution is visible in relevant dashboards or lists.
- An entry is created in the
audit_logstable recording the creation of the institution.
- Access Institutions Management: The user navigates to the "Institutions Management" section.
- Initiate New Institution Creation: The user clicks an "Add New Institution" (or similar) button.
-
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) fromSectorTypeenum. -
description: Textual description. -
location_id: Selected via a map interface or by choosing an existing location from thelocationstable. -
parent_institution_id: Optional, for hierarchical relationships (referencesinstitutions.id). - Specific fields if creating a
medical_centerorbase_rescue(e.g.,level,total_bedsfor medical centers).
-
- Fill Form Details: The user enters the required information. Client-side validation provides immediate feedback on format or missing required fields.
- Submit Form: The user clicks "Save" or "Create Institution."
- 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.
-
API Call: The frontend sends a
POSTrequest to an endpoint like/api/institutionswith the form data. -
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
institutionstable. - If applicable, creates related records (e.g., in
medical_centersorbase_rescues). - Creates an entry in the
audit_logstable.
- Creates a new record in the
-
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.
-
Success (
- Cancellation: The user can click "Cancel" at any point before final submission to discard changes and return to the previous view.
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;
-
Transaction Management: Backend operations involving multiple table inserts (e.g.,
institutionsandmedical_centers) should be wrapped in a database transaction to ensure atomicity. -
Location Handling: Consider allowing creation of a new
locationsrecord 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_centerorbase_rescue, the API endpoint might be more specific (e.g.,/api/medical-centers) or the main/api/institutionsendpoint might accept atypeparameter to handle the creation of specialized records.
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.
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:
- User is authenticated and authorized to create events.
- An external report of an incident has been received.
Postconditions:
- A new event record is created in the
eventstable. - The new event is visible on the "Event Dashboard" or relevant operational views.
- An entry is created in
audit_logs. - Optionally, an initial entry might be made in
communications_logif the report itself is considered a significant communication.
- Receive External Report: Dispatcher receives information about an incident.
- Access Event Creation Interface: Dispatcher navigates to the "Event Dashboard" and clicks "Create New Event."
-
Display Event Form: The system presents the "Create Event" form. Key fields include:
-
event_type: (e.g.,medical_emergency,fire_incident) fromEventCategoryenum. -
location_id: Selected via map or address input (linked tolocationstable). -
reported_time: Defaults tonow(), can be adjusted. -
description: Detailed text about the incident. -
priority_level: (e.g.,critical,high) fromPriorityLevelenum. -
triage_status: Initial assessment (e.g.,unknown,red) fromTriageStatusenum. -
people_affected: Estimated number. -
reported_by_text: Free-text field for who reported the event.
-
- Fill Event Form: Dispatcher enters incident details. Client-side validation provides immediate feedback.
- Submit Event: Dispatcher clicks "Create Event" or "Save."
- Client-Side Validation & UI Feedback: Final client-side checks. Loading indicator may appear.
-
API Call: Frontend sends
POST /api/eventswith form data. -
Backend Processing:
- Authentication & Authorization.
- Server-Side Validation (e.g., valid
location_id, enum values). - Database Operations:
- Creates a new record in the
eventstable. - Creates an entry in
audit_logs. - (Optional) Creates an entry in
communications_log.
- Creates a new record in the
-
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.
-
Success (
- Cancellation: User can cancel before final submission.
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;
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).
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:
- An event exists in the system (e.g.,
status: 'pending'orstatus: 'active'). - User is authenticated and authorized to manage events.
- Available institutions and resources exist in the system.
Postconditions:
- Selected institutions are linked to the event via
event_institutions. - Selected resources are assigned to the event via
event_resources, and theiravailable_unitsandstatusin theresourcestable are updated. - The event's
statusin theeventstable is updated. - All actions are recorded in
audit_logs.
- Access Event Details: User is viewing the detail page of an active event.
- Initiate Institution Assignment: User clicks "Assign Institution."
-
Select Institutions: UI presents a list/search/map to select one or more relevant institutions (from
institutionstable). - Confirm Assignment: User confirms selections.
-
API Call:
POST /api/events/{event_id}/institutionswith selected institution IDs. -
Backend Processing:
- Validate event and institution IDs.
- Create records in
event_institutions. - Log in
audit_logs.
- UI Feedback: Success message; assigned institutions list updates on event page.
- Access Event Details: User is viewing the event detail page.
- Initiate Resource Assignment: User clicks "Assign Resource."
-
Select Resources: UI presents a list/search of available resources (from
resourcestable), allowing selection and quantity specification. - Confirm Assignment: User confirms.
-
API Call:
POST /api/events/{event_id}/resourceswith selected resource IDs and quantities. -
Backend Processing:
- Validate event, resource IDs, and available quantity.
- Create records in
event_resources. - Update
resources.available_unitsandresources.status(e.g., toassigned). - Log in
audit_logs.
- UI Feedback: Success message; assigned resources list updates; resource availability reflects changes.
- Access Event Details: User is viewing the event detail page.
- Initiate Status Update: User clicks "Update Status" or selects a new status from a dropdown.
-
Select New Status: User chooses a new status from the
EventStatusenum (e.g.,en_route,resolved). - Confirm Update: User confirms.
-
API Call:
PUT /api/events/{event_id}orPATCH /api/events/{event_id}/statuswith the new status. -
Backend Processing:
- Validate event ID and new status.
- Update
events.status(andevents.ended_atif status isresolvedorclosed). - Log in
audit_logs.
- UI Feedback: Success message; event status display updates.
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"];
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.
Part 1: Admin Sends Invitation
- Access User Management: Admin navigates to the user management section.
- Initiate Invitation: Admin clicks "Invite New User."
-
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 (fromRoleenum, e.g.,standard,manager).
-
- Send Invite: Admin submits the form.
-
API Call:
POST /api/inviteswith invitation details. -
Backend Processing:
- Validate data (e.g., email format, valid
institution_id, validrole). - Generate a unique, expiring
token. - Create a record in the
invitestable (statussent,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.
- Validate data (e.g., email format, valid
- UI Feedback: Admin sees a success message.
Part 2: New User Accepts Invitation & Registers
- Receive Email: Invitee receives the invitation email.
-
Click Registration Link: Invitee clicks the link, which navigates to a registration page on StateForce, passing the
token. -
Display Registration Form: The registration form may pre-fill the email. User needs to provide:
first_namelast_name-
password(and confirmation)
- Submit Registration: User submits the form.
-
API Call:
POST /api/users/register(or similar) with registration details and thetoken. -
Backend Processing:
- Validate the
tokenfrom theinvitestable (exists, not expired, statussent). - Validate user input (password strength, etc.).
- Create a new record in the
userstable (setconfirmedtotrue). - Create a record in
user_institutionslinking the new user to theinstitution_idandrolefrom theinvitesrecord. - Update the
invitesrecord (statusaccepted,used_at). - Log in
audit_logs.
- Validate the
- 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.
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;
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.
This flow describes how an administrator updates a user's role within one of their associated institutions.
Actor: Admin or Superadmin
Preconditions:
- User is authenticated and authorized to manage user roles.
- The target user exists and is associated with the institution in question (record in
user_institutions).
Postconditions:
- The user's
rolein the specifieduser_institutionsrecord is updated. - An entry is created in
audit_logs.
- Access User Profile: Admin navigates to the target user's profile page, which lists their institutional associations and roles.
-
Select Institution for Role Change: Admin identifies the specific
user_institutionsentry to modify. - Initiate Role Edit: Admin clicks an "Edit Role" button for that specific institutional assignment.
-
Choose New Role: A dropdown or selection list appears with available roles from the
Roleenum. Admin selects the new role. - Confirm Change: Admin confirms the new role selection.
-
API Call:
PUT /api/user-institutions/{user_id}/{institution_id}(or similar, using the composite key or a dedicated ID ifuser_institutionshas one) with the new role. -
Backend Processing:
- Authentication & Authorization.
- Validate that the
user_institutionsrecord exists. - Update the
rolefield in the identifieduser_institutionsrecord. - Create an entry in
audit_logs(capturingold_valueandnew_valuefor the role).
-
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 theuser_institutionsrecord doesn't exist. -
Validation Error (
422 Unprocessable Entity): If the new role is invalid. -
Server Error (
500 Internal Server Error): UI displays generic error.
-
Success (
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;
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).
Part 1: Creating a Generic Contact
- Access Contacts Directory: User (Admin/Manager) navigates to the contacts management section.
- Initiate New Contact: User clicks "Create New Contact."
-
Fill Contact Form: User enters:
name-
email(unique) -
radio_frequency(optional) - Associated phone numbers can be added in a subsequent step or integrated here.
- Submit Contact: User saves the form.
-
API Call:
POST /api/contacts. -
Backend Processing: Validate (unique email), create record in
contacts, log inaudit_logs. - UI Feedback: Success message, new contact appears in directory.
Part 2: Linking Contact to an Institution
- Access Contact Profile or Institution Profile: User navigates to either the contact's detail page or the institution's detail page.
- Initiate Linking: User clicks "Link Contact to Institution" (from contact page) or "Add Institution Contact" (from institution page).
-
Select Contact/Institution & Type:
- If on contact page: Search/select institution, select
contact_type(fromContactTypesenum). - If on institution page: Search/select contact, select
contact_type.
- If on contact page: Search/select institution, select
- Confirm Link: User confirms.
-
API Call:
POST /api/institution-contacts(or similar, e.g.,POST /api/institutions/{id}/contacts). -
Backend Processing: Validate IDs, create record in
institution_contacts(using composite key:institution_id,contact_id,contact_type), log inaudit_logs. - UI Feedback: Success message, link is displayed.
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;
7. π Registering and Transferring a Patient (Simplified from #8 in prompt, assuming patients table is not directly in schema but managed via event context)
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.
Part 1: Logging Patient Information within an Event
-
Actor:
Paramedic(Standard User) orDispatcher -
Action: When an event is created or updated (
eventstable), details about affected individuals are recorded inevents.description,events.people_affected, and potentially in linkednotes(viaevent_notes). Theevents.triage_statusreflects the overall severity.
Part 2: "Transferring" a Patient (Assigning Transport Resource and Destination Institution)
-
Actor:
DispatcherorManager -
Action:
-
Identify Need: Based on event details and patient information (in
events.descriptionornotes), a decision is made to "transfer" (i.e., transport) affected individuals. -
Assign Transport Resource: An available ambulance (
resourcestable, type 'Ambulance') is assigned to the event viaevent_resources. Its status changes toassigned. -
Assign Destination Facility: A medical center (
institutionstable, type 'Medical Center') is assigned to the event as a destination viaevent_institutions. -
Update Event/Resource Status:
- The ambulance's status (in
resources) might be updated (e.g.,en_route_to_hospital, thenat_hospital, thenavailableafter drop-off). - The event's status (
events.status) might be updated (e.g.,patient_en_route,patient_arrived_at_facility). - Notes in
event_noteswould track the patient's movement and handoff.
- The ambulance's status (in
-
Identify Need: Based on event details and patient information (in
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"];
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.
Dispatchers at the CRUM log significant communications (radio, phone) related to an active event into the communications_log table for audit and reference.
- Access Event: Dispatcher is on an active event's detail page.
- Initiate Log: Clicks "Log Communication."
-
Fill Log Form:
-
channel: (e.g.,radio,phone) - This field is not incommunications_logbut is good practice, could be indescription. -
from_text/to_text: Free text for sender/receiver. Schema hasfrom_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.
-
- Submit Log: Clicks "Save Log."
-
API Call:
POST /api/communications-log(orPOST /api/events/{id}/communications). -
Backend Processing: Validate, create record in
communications_log, link toevent_idanduser_id, log inaudit_logs. - UI Feedback: Success message, log appears in event's communication timeline.
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;
Superadmins and Admins review the audit_logs table to track actions performed within the system for accountability and security.
- Access Audit Logs: User navigates to the "Audit Logs" section in System Administration.
- Default View: Shows recent logs, sortable and paginated.
-
Apply Filters: User can filter by:
-
entity_name(e.g.,events,users) entity_id-
action(fromLogActionsenum:created,updated,delete) -
user_id(who performed the action) - Date Range (
created_atof the log entry)
-
- Retrieve Logs: User applies filters.
-
API Call:
GET /api/audit-logswith filter parameters. -
Backend Processing: Query
audit_logstable based on filters, with pagination. -
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).
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"];
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.
- Access Calendar: Manager navigates to the calendar module.
- Initiate New Event: Clicks "Create Calendar Event."
-
Fill Event Form:
-
title,description -
scheduled_at,ends_at(orduration) -
priority(fromPriorityLevelenum) -
visibility(fromVisibilityenum) -
recurrence_rule,repeat_until(if recurring) - Link to
event_id(optional, if calendar entry is for a specific emergency event) - Link to
institution_id(viacalendar_entries_institutionstable)
-
- Submit Event: Clicks "Save Event."
-
API Call:
POST /api/calendar-entries. -
Backend Processing: Validate, create
calendar_entriesrecord, createcalendar_entries_institutionsrecord, log inaudit_logs. - UI Feedback: Success message, event appears on calendar.
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
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).
- Access Entity: User is viewing an entity's detail page (e.g., an event).
- Initiate File Upload: Clicks "Attach File."
-
Select File & Metadata: User selects a file from their device and optionally adds
description,visibility.file_typemight be auto-detected or selected. - Upload File: Clicks "Upload."
-
API Call:
POST /api/attachments(orPOST /api/events/{id}/attachments). File is sent as multipart/form-data. -
Backend Processing:
- Validate file (size, type).
- Store file (e.g., S3, local disk) and get
file_url. - Create
attachmentsrecord (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_attachmentslinkingevent_idand newattachment_id). - Log in
audit_logs.
- UI Feedback: Success message, attachment appears in entity's attachments list.
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
- 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
Visibilityenum on tables likenotesandattachmentsis 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.
We are always looking for feedback and contributions to improve StateForce. Feel free to open issues, suggest edits, or submit pull requests to the repository.
- Repo: StateForce GitHub
- Contact: martinmendozadev@gmail.com
If you encounter issues or need assistance, please reach out via:
- Email: martinmendozadev@gmail.com
- GitHub Issues: Submit an Issue
This documentation and the StateForce platform are licensed under the Apache License 2.0.
Thank you for using StateForce! π¨
Together, we are improving emergency response operations in real-time.
Welcome to the StateForce Wiki! Use this sidebar to navigate through the documentation.
This sidebar provides quick access to all the documentation pages. For detailed information, click on the desired section.