# Login Process Documentation

## Login Sequence Diagram

```mermaid
sequenceDiagram
    actor User
    participant Login as Login Component
    participant API as Auth API
    participant QSP as QSP API
    participant Session as Session Store
    participant Router as Next Router

    User->>Login: Enter credentials
    Login->>Login: Validate input
    alt Invalid Input
        Login->>User: Show error message
    else Valid Input
        Login->>API: POST /api/auth
        API->>QSP: POST /api/user/login
        QSP-->>API: Return user data

        alt Login Success
            API->>Session: Create session
            Session->>Session: Set user data
            Session->>Session: Set role
            API-->>Login: Return success response
            Login->>Router: Redirect to home
            Router->>User: Show home page
        else Login Failed
            API-->>Login: Return error response
            Login->>User: Show error message
        end
    end
```

## Login Process Flow

1. **User Input**

   - User enters login credentials (ID and password)
   - Optional: User can toggle Q.PARTNERS mode
   - Optional: User can save ID

2. **Input Validation**

   - Checks if ID and password are not empty
   - Validates email format for Q.PARTNERS mode

3. **Authentication Request**

   - Sends credentials to Auth API
   - Auth API forwards request to QSP API
   - QSP API validates credentials

4. **Session Management**

   - On successful login:
     - Creates new session
     - Stores user data
     - Sets user role based on permissions
     - Saves session to cookies

5. **Response Handling**
   - Success: Redirects to home page
   - Failure: Shows error message

## Role Assignment Logic

The system assigns roles based on the following rules:

- `T01`: If userId is 'T01'
- `Admin`: If groupId is '60000'
- `Admin_Sub`: If groupId is '70000' and builderNo is null
- `Builder`: If groupId is '70000' and builderNo is not null
- `User`: Default role for all other cases

```mermaid
graph TD
subgraph Root
A[RootLayout] --> B[ReactQueryProviders]
B --> C[EdgeProvider]
C --> D[HTML Structure]
end
    subgraph Layout Components
        D --> E[Header]
        D --> F[Main Content]
        D --> G[Footer]
        D --> H[Float Button]
        D --> I[PopupController]
    end
    subgraph Pages
        F --> J[Login]
        F --> K[Survey Sale]
        F --> L[Suitable]
        F --> M[Inquiry]
        F --> N[Password Reset]
        F --> O[PDF]
    end
    subgraph Providers
        P1[ReactQueryProvider]
        P2[EdgeProvider]
    end
    subgraph Components
        C1[UI Components]
        C2[Popup Components]
        C3[PDF Components]
        C4[Survey Components]
        C5[Inquiry Components]
    end
    subgraph Utils
        U1[Session Management]
        U2[Mailer]
        U3[API Routes]
    end
    %% Relationships
    A --> P1
    A --> P2
    J --> U1
    K --> C4
    L --> C4
    M --> C5
    N --> U2
    O --> C3
```
