%% Royal Enfield Workflow Management System
%% Entity Relationship Diagram
%% Database: PostgreSQL 16.x

erDiagram
%% Core Tables

users ||--o{ workflow_requests : "initiates"
users ||--o{ approval_levels : "approves"
users ||--o{ participants : "participates"
users ||--o{ work_notes : "posts"
users ||--o{ documents : "uploads"
users ||--o{ activities : "performs"
users ||--o{ notifications : "receives"
users ||--o{ user_sessions : "has"
users ||--o{ users : "reports_to"

workflow_requests ||--|{ approval_levels : "has"
workflow_requests ||--o{ participants : "involves"
workflow_requests ||--o{ documents : "contains"
workflow_requests ||--o{ work_notes : "has"
workflow_requests ||--o{ activities : "logs"
workflow_requests ||--o{ tat_tracking : "monitors"
workflow_requests ||--o{ notifications : "triggers"
workflow_requests ||--|| conclusion_remarks : "concludes"

approval_levels ||--o{ tat_tracking : "tracks"

work_notes ||--o{ work_note_attachments : "has"

notifications ||--o{ email_logs : "sends"
notifications ||--o{ sms_logs : "sends"

%% Entity Definitions

users {
    uuid user_id PK
    varchar employee_id UK "HR System ID - Optional"
    varchar okta_sub UK "Okta Subject ID"
    varchar email UK "Primary Email"
    varchar first_name "Optional"
    varchar last_name "Optional"
    varchar display_name "Full Name"
    varchar department "Optional"
    varchar designation "Optional"
    varchar phone "Office Phone - Optional"
    varchar manager "Reporting Manager - SSO Optional"
    varchar second_email "Alternate Email - SSO Optional"
    text job_title "Detailed Job Title - SSO Optional"
    varchar employee_number "HR Employee Number - SSO Optional"
    varchar postal_address "Work Location - SSO Optional"
    varchar mobile_phone "Mobile Contact - SSO Optional"
    jsonb ad_groups "AD Group Memberships - SSO Optional"
    jsonb location "Location Details - Optional"
    boolean is_active "Account Status Default true"
    enum role "USER, MANAGEMENT, ADMIN - RBAC Default USER"
    timestamp last_login "Last Login Time"
    timestamp created_at "Record Created"
    timestamp updated_at "Record Updated"
}

workflow_requests {
    uuid request_id PK
    varchar request_number UK "REQ-YYYY-NNNNN"
    uuid initiator_id FK
    varchar template_type "CUSTOM or TEMPLATE"
    varchar title "Request Summary"
    text description "Detailed Description"
    enum priority "STANDARD or EXPRESS"
    enum status "DRAFT to CLOSED"
    integer current_level "Active Stage"
    integer total_levels "Max 10 Levels"
    decimal total_tat_hours "Cumulative TAT"
    timestamp submission_date
    timestamp closure_date
    text conclusion_remark "Final Summary"
    text ai_generated_conclusion "AI Version"
    boolean is_draft "Saved Draft"
    boolean is_deleted "Soft Delete"
    timestamp created_at
    timestamp updated_at
}

approval_levels {
    uuid level_id PK
    uuid request_id FK
    integer level_number "Sequential Level"
    varchar level_name "Optional Label"
    uuid approver_id FK
    varchar approver_email
    varchar approver_name
    decimal tat_hours "Level TAT"
    integer tat_days "Calculated Days"
    enum status "PENDING to APPROVED"
    timestamp level_start_time "Timer Start"
    timestamp level_end_time "Timer End"
    timestamp action_date "Decision Time"
    text comments "Approval Notes"
    text rejection_reason
    boolean is_final_approver "Last Level"
    decimal elapsed_hours "Time Used"
    decimal remaining_hours "Time Left"
    decimal tat_percentage_used "Usage %"
    timestamp created_at
    timestamp updated_at
}

participants {
    uuid participant_id PK
    uuid request_id FK
    uuid user_id FK
    varchar user_email
    varchar user_name
    enum participant_type "SPECTATOR etc"
    boolean can_comment "Permission"
    boolean can_view_documents "Permission"
    boolean can_download_documents "Permission"
    boolean notification_enabled
    uuid added_by FK
    timestamp added_at
    boolean is_active
}

documents {
    uuid document_id PK
    uuid request_id FK
    uuid uploaded_by FK
    varchar file_name "Storage Name"
    varchar original_file_name "Display Name"
    varchar file_type
    varchar file_extension
    bigint file_size "Bytes (Max 10MB)"
    varchar file_path "Cloud Path"
    varchar storage_url "Public URL"
    varchar mime_type
    varchar checksum "SHA-256"
    boolean is_google_doc
    varchar google_doc_url
    enum category "Document Type"
    integer version "Version Number"
    uuid parent_document_id FK "Version Parent"
    boolean is_deleted
    integer download_count
    timestamp uploaded_at
}

work_notes {
    uuid note_id PK
    uuid request_id FK
    uuid user_id FK
    varchar user_name
    varchar user_role "INITIATOR etc"
    text message "Max 2000 chars"
    varchar message_type "COMMENT etc"
    boolean is_priority "Urgent Flag"
    boolean has_attachment
    uuid parent_note_id FK "Threading"
    uuid[] mentioned_users "@Tagged Users"
    jsonb reactions "Emoji Responses"
    boolean is_edited
    boolean is_deleted
    timestamp created_at
    timestamp updated_at
}

work_note_attachments {
    uuid attachment_id PK
    uuid note_id FK
    varchar file_name
    varchar file_type
    bigint file_size
    varchar file_path
    varchar storage_url
    boolean is_downloadable
    integer download_count
    timestamp uploaded_at
}

activities {
    uuid activity_id PK
    uuid request_id FK
    uuid user_id FK "NULL for System"
    varchar user_name
    varchar activity_type "Event Type"
    text activity_description
    varchar activity_category "Classification"
    varchar severity "INFO to CRITICAL"
    jsonb metadata "Additional Context"
    boolean is_system_event
    varchar ip_address
    text user_agent
    timestamp created_at
}

notifications {
    uuid notification_id PK
    uuid user_id FK
    uuid request_id FK
    varchar notification_type "Event Type"
    varchar title
    text message
    boolean is_read
    enum priority "LOW to URGENT"
    varchar action_url
    boolean action_required
    jsonb metadata
    varchar[] sent_via "IN_APP, EMAIL, SMS"
    boolean email_sent
    boolean sms_sent
    boolean push_sent
    timestamp read_at
    timestamp expires_at
    timestamp created_at
}

tat_tracking {
    uuid tracking_id PK
    uuid request_id FK
    uuid level_id FK "NULL for Request"
    varchar tracking_type "REQUEST or LEVEL"
    enum tat_status "ON_TRACK to BREACHED"
    decimal total_tat_hours
    decimal elapsed_hours
    decimal remaining_hours
    decimal percentage_used
    boolean threshold_50_breached
    timestamp threshold_50_alerted_at
    boolean threshold_80_breached
    timestamp threshold_80_alerted_at
    boolean threshold_100_breached
    timestamp threshold_100_alerted_at
    integer alert_count
    timestamp last_calculated_at
}

conclusion_remarks {
    uuid conclusion_id PK
    uuid request_id FK
    text ai_generated_remark "AI Output"
    varchar ai_model_used "GPT-4 etc"
    decimal ai_confidence_score "0.00 to 1.00"
    text final_remark "User Edited"
    uuid edited_by FK
    boolean is_edited
    integer edit_count
    jsonb approval_summary
    jsonb document_summary
    text[] key_discussion_points
    timestamp generated_at
    timestamp finalized_at
}

audit_logs {
    uuid audit_id PK
    uuid user_id FK
    varchar entity_type "Table Name"
    uuid entity_id "Record ID"
    varchar action "CREATE, UPDATE etc"
    varchar action_category
    jsonb old_values "Before"
    jsonb new_values "After"
    text changes_summary
    varchar ip_address
    text user_agent
    varchar session_id
    varchar request_method "GET, POST etc"
    varchar request_url
    integer response_status "HTTP Code"
    integer execution_time_ms
    timestamp created_at
}

user_sessions {
    uuid session_id PK
    uuid user_id FK
    varchar session_token UK "JWT Access"
    varchar refresh_token "JWT Refresh"
    varchar ip_address
    text user_agent
    varchar device_type "WEB, MOBILE"
    varchar browser
    varchar os
    timestamp login_at
    timestamp last_activity_at
    timestamp logout_at
    timestamp expires_at
    boolean is_active
    varchar logout_reason
}

email_logs {
    uuid email_log_id PK
    uuid request_id FK
    uuid notification_id FK
    varchar recipient_email
    uuid recipient_user_id FK
    text[] cc_emails
    text[] bcc_emails
    varchar subject
    text body
    varchar email_type
    varchar status "QUEUED to SENT"
    integer send_attempts
    timestamp sent_at
    timestamp failed_at
    text failure_reason
    timestamp opened_at
    timestamp clicked_at
    timestamp created_at
}

sms_logs {
    uuid sms_log_id PK
    uuid request_id FK
    uuid notification_id FK
    varchar recipient_phone
    uuid recipient_user_id FK
    text message
    varchar sms_type
    varchar status "QUEUED to DELIVERED"
    integer send_attempts
    timestamp sent_at
    timestamp delivered_at
    timestamp failed_at
    text failure_reason
    varchar sms_provider
    varchar sms_provider_message_id
    decimal cost
    timestamp created_at
}

system_settings {
    uuid setting_id PK
    varchar setting_key UK "CONFIG_NAME"
    text setting_value "Value"
    varchar setting_type "STRING, NUMBER etc"
    varchar setting_category "TAT, NOTIFICATION"
    text description
    boolean is_editable
    boolean is_sensitive "Encrypted"
    jsonb validation_rules
    text default_value
    uuid updated_by FK
    timestamp created_at
    timestamp updated_at
}

workflow_templates {
    uuid template_id PK
    varchar template_name "Future Scope"
    text template_description
    varchar template_category
    jsonb approval_levels_config
    decimal default_tat_hours
    boolean is_active
    integer usage_count
    uuid created_by FK
    timestamp created_at
    timestamp updated_at
}

report_cache {
    uuid cache_id PK
    varchar report_type
    jsonb report_params "Input Filters"
    jsonb report_data "Cached Result"
    uuid generated_by FK
    timestamp generated_at
    timestamp expires_at
    integer access_count
    timestamp last_accessed_at
}


%% Notes and Constraints
%% 1. All timestamps are WITH TIME ZONE
%% 2. UUIDs are generated via uuid-ossp extension
%% 3. Enums are custom types defined separately
%% 4. JSONB used for flexible metadata storage
%% 5. Soft deletes via is_deleted flags
%% 6. Audit trail via activities and audit_logs
%% 7. Multi-channel notifications (in-app, email, SMS, push)
%% 8. TAT thresholds: 50%, 80%, 100%
%% 9. Max approval levels: 10
%% 10. Max file size: 10 MB