# Sign-up Page Documentation ## Overview The sign-up page allows new users to register for the DRIVE360 platform. It collects user information, assigns users to the Lapanga location by default, and allows them to select their working area from a dropdown populated from the database. ## UI Components The sign-up page includes the following input fields: - Name (text input) - Username (text input) - Phone Number (telephone input) - Location (disabled text field, pre-filled with "Lapanga") - Working Area (dropdown, populated from database) - Password (password input) - Re-Enter Password (password input for confirmation) - Photo (optional file upload) ## API Endpoints ### 1. Fetch Working Areas **Endpoint:** GET `/api/working-areas` **Purpose:** Retrieves all working areas from the database to populate the dropdown **Response:** JSON object containing an array of working areas with their GroupIDs and Names **Error Handling:** Returns a 500 error if database connection fails **Frontend API Function:** ```javascript // Function to fetch working areas for signup export const fetchWorkingAreas = async () => { const baseUrl = await getApiBaseUrl(); try { const response = await fetchWithRetry(`${baseUrl}/working-areas`); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Failed to fetch working areas'); } return await response.json(); } catch (error) { console.error('Error fetching working areas:', error); throw error; } }; ``` **Backend Endpoint Implementation:** ```javascript // API endpoint to fetch working areas for signup form router.get('/working-areas', async (req, res) => { try { const connection = await mysql.createConnection(dbConfig); // Fetch all working areas const [workingAreas] = await connection.execute( 'SELECT GroupID, WorkingAreaName FROM UserWorkingArea ORDER BY WorkingAreaName' ); await connection.end(); res.json({ workingAreas }); } catch (error) { console.error('Error fetching working areas:', error); res.status(500).json({ error: 'Failed to fetch working areas' }); } }); ``` ### 2. Register New User **Endpoint:** POST `/api/signup` **Purpose:** Registers a new user with the provided information **Request Body:** - name: User's full name - username: Unique username/employee ID - phone: Phone number - password: User's password - groupId: Selected working area's GroupID - photo: Optional base64-encoded user photo **Response:** JSON object with success message and userPK **Error Handling:** Returns appropriate error status and message for validation failures or database errors **Frontend API Call Implementation:** ```javascript // Direct fetch implementation in SignUp.js component const response = await fetch(`http://eframeehs.in:${serverPort}/api/signup`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: form.name, username: form.username, phone: form.phone, password: form.password, groupId: form.groupId, photo: photoBase64 }), }); ``` **Backend Endpoint Implementation:** ```javascript // API endpoint for user signup router.post('/signup', async (req, res) => { const { name, username, phone, password, groupId } = req.body; const photo = req.body.photo || null; if (!name || !username || !phone || !password || !groupId) { return res.status(400).json({ error: 'Name, Username, Phone, Password, and Working Area are required' }); } try { const connection = await mysql.createConnection(dbConfig); // Check if username already exists const [existingUsers] = await connection.execute( 'SELECT UserPK FROM Users WHERE EmployeeID = ?', [username] ); if (existingUsers.length > 0) { await connection.end(); return res.status(409).json({ error: 'Username already exists' }); } // Use LocationID 2 for "Lapanga" const locationID = 2; // Directly using LocationID 2 for Lapanga // Insert new user with roleId = 1 and the selected groupId const [result] = await connection.execute( `INSERT INTO Users (EmployeeName, EmployeeID, Password, LocationID, GroupID, RoleID, PhoneNumber, photo) VALUES (?, ?, ?, ?, ?, 1, ?, ?)`, [name, username, password, locationID, groupId, phone, photo] ); await connection.end(); res.status(201).json({ message: 'User registered successfully', userPK: result.insertId }); } catch (error) { console.error('Database error during signup:', error); res.status(500).json({ error: 'Internal server error' }); } }); ``` ## SQL Queries ### 1. Fetch Working Areas ```sql SELECT GroupID, WorkingAreaName FROM UserWorkingArea ORDER BY WorkingAreaName ``` **Purpose:** Retrieves all working areas from the UserWorkingArea table, sorted alphabetically by name ### 2. Check Existing Username ```sql SELECT UserPK FROM Users WHERE EmployeeID = ? ``` **Purpose:** Checks if a username (EmployeeID) already exists in the database ### 3. Get Location ID ```sql SELECT LocationID FROM UserLocation WHERE LocationName = ? ``` **Purpose:** Retrieves the LocationID for "Lapanga" location (no longer used, now hardcoded as 2) ### 4. Insert New User ```sql INSERT INTO Users (EmployeeName, EmployeeID, Password, LocationID, GroupID, RoleID, PhoneNumber, photo) VALUES (?, ?, ?, ?, ?, 1, ?, ?) ``` **Purpose:** Inserts a new user record with the provided information **Parameters:** 1. EmployeeName: User's full name 2. EmployeeID: Unique username/employee ID 3. Password: User's password (plain text, should consider hashing in production) 4. LocationID: ID of "Lapanga" location (hardcoded as 2) 5. GroupID: Selected working area ID 6. RoleID: Fixed value of 1 7. PhoneNumber: User's phone number 8. photo: Base64-encoded user photo (can be null) ## Database Tables ### 1. Users The main users table that stores all user information: - UserPK: Primary key (auto-increment) - EmployeeName: User's full name - EmployeeID: Unique username/employee ID - Password: User's password - LocationID: Foreign key to UserLocation table - GroupID: Foreign key to UserWorkingArea table - RoleID: Role ID (always 1 for regular users) - PhoneNumber: User's phone number - photo: BLOB data for user's profile photo (optional) ### 2. UserLocation Stores location information: - LocationID: Primary key - LocationName: Name of the location (e.g., "Renukut") ### 3. UserWorkingArea Stores working area information: - GroupID: Primary key - WorkingAreaName: Name of the working area (e.g., "Pot Area", "Cast House", etc.) ## Sign-up Workflow 1. **Page Load:** - User accesses the sign-up page - Frontend fetches working areas from `/api/working-areas` endpoint - Dropdown is populated with working areas from the database 2. **Form Filling:** - User enters their name, username, phone number - Location is pre-filled with "Lapanga" and disabled - User selects their working area from the dropdown - User enters and confirms their password - User optionally uploads a profile photo 3. **Validation (Client-side):** - All required fields are checked - Password and confirm password are compared for match - Basic format validation for phone number 4. **Form Submission:** - Form data is collected - Photo is converted to base64 if provided - Request is sent to `/api/signup` endpoint 5. **Server-side Processing:** - Backend validates all required fields - Checks if username already exists - Uses LocationID 2 for "Lapanga" location - Inserts new user record with all fields including: - Fixed RoleID = 1 - Selected GroupID from the form - LocationID for "Lapanga" (hardcoded as 2) 6. **Response Handling:** - On success, user is redirected to login page - On error, appropriate error message is displayed ## Error Handling 1. **Server Connection Errors:** - Frontend shows "Connection to server failed" message if server is not running - Suggests starting the server on port 3009 2. **Validation Errors:** - Missing required fields: 400 Bad Request - Password mismatch: Handled on client-side - Username already exists: 409 Conflict 3. **Database Errors:** - Location not found: 500 Internal Server Error - General database errors: 500 Internal Server Error with detailed logging on server ## Troubleshooting 1. **"Connection to server failed" Error:** - Ensure the server is running by executing `start-server.bat` - Check if port 3009 is available or modify server.js to use a different port 2. **"Username already exists" Error:** - Choose a different username that is not already in the database 3. **"Location not found" Error:** - This error no longer occurs as the LocationID is hardcoded as 2 for "Lapanga" 4. **Working Area Dropdown Empty:** - Check if the UserWorkingArea table is populated with working areas - Verify database connection settings in config/database.js 5. **Photo Upload Issues:** - Ensure the photo size is reasonable (under 1MB recommended) - Only image file types are supported (JPEG, PNG, GIF, etc.) ## Deployment Considerations 1. **Database Configuration:** - Update database credentials in config/database.js for production - Consider implementing password hashing for security 2. **Server Port:** - The server is configured to run on port 3009 - Update server.js and SignUp.js if a different port is needed 3. **Security:** - Currently passwords are stored in plain text - Implement password hashing and salting for production - Consider adding HTTPS for secure transmission