# React Native Offline Attendance App - Development Prompt

## Prompt for ChatGPT

---

**You are an expert React Native developer. I need you to create a complete offline-capable attendance mobile application using React Native that integrates with an existing backend API.**

---

## Project Overview

Create a **React Native mobile application** for employee attendance tracking with **full offline capability**. The app should work seamlessly both online and offline, syncing data when connectivity is restored.

---

## Core Requirements

### 1. Technology Stack
- **Framework:** React Native (with Expo or bare React Native)
- **State Management:** Redux Toolkit or Zustand
- **Local Storage:** AsyncStorage or SQLite (for offline data)
- **API Calls:** Axios with retry logic
- **UI Library:** React Native Paper or Native Base
- **Navigation:** React Navigation
- **Camera:** react-native-camera or expo-camera (for QR scanning)
- **Network Detection:** @react-native-community/netinfo

### 2. App Features

#### A. Authentication
- Login screen with username/password
- Remember login credentials securely (using react-native-keychain)
- Logout functionality
- Session management

#### B. Employee Management
- Fetch and display list of all employees
- Search employees by name or employee number
- Display employee details:
  - Employee Number
  - Full Name
  - QR Code
  - Department
  - Location
  - Account Status
- Cache employee data locally for offline access

#### C. Attendance Recording (Core Feature)
- **Sign In / Sign Out** buttons
- **Lunch Start / Lunch End** buttons
- **QR Code Scanner** for quick attendance
  - Scan employee QR code
  - Auto-detect action (sign-in/sign-out based on current status)
  - Visual feedback on successful scan
- **Manual Entry** option
  - Select employee from list
  - Choose action type
- **Offline Mode:**
  - Record attendance locally when offline
  - Store with unique `local_uuid`
  - Display "Offline Mode" indicator
  - Show pending sync count
- **Facial Recognition** (Optional/Future)
  - Take photo during attendance
  - Store photo with attendance record

#### D. Attendance History
- View today's attendance records
- View attendance history (last 7 days)
- Filter by employee
- Show sync status (synced/pending)
- Display timestamps for all events

#### E. Synchronization
- **Automatic Sync:**
  - Detect when internet connection is restored
  - Automatically sync pending records
  - Show sync progress
  - Retry failed syncs
- **Manual Sync:**
  - Pull-to-refresh on lists
  - Manual sync button
  - Display last sync time
- **Sync Queue:**
  - Display pending records count
  - View pending records
  - Option to clear/retry individual records
- **Conflict Handling:**
  - Handle "Already synced" responses gracefully
  - Remove duplicates from local storage

#### F. Dashboard/Home Screen
- Today's statistics:
  - Total employees
  - Present employees
  - Attendance rate
  - Pending sync count
- Quick actions:
  - Scan QR Code
  - View Employees
  - View History
- Sync status indicator
- Network status indicator

---

## API Integration

### Base URL
```
http://your-domain.com/public/api
```

### API Endpoints to Integrate

#### 1. Get All Employees
**Endpoint:** `GET /api/employees`

**Response:**
```json
{
  "status": "success",
  "total": 150,
  "data": [
    {
      "employee_number": "EMP001",
      "qr_code": "QR123456789",
      "full_name": "John Doe",
      "department": "IT Department",
      "location": "Main Office",
      "account_status": "Active"
    }
  ]
}
```

#### 2. Get Single Employee
**Endpoint:** `GET /api/employees/{employee_number_or_qr_code}`

**Response:**
```json
{
  "status": "success",
  "data": {
    "employee_number": "EMP001",
    "qr_code": "QR123456789",
    "full_name": "John Doe",
    "email": "john@company.com",
    "phone": "0712345678",
    "department": "IT Department",
    "location": "Main Office",
    "account_status": "Active"
  }
}
```

#### 3. Sync Attendance (Main Endpoint)
**Endpoint:** `POST /api/attendance/sync`

**Request Body:**
```json
{
  "local_uuid": "device-12345-record-67890",
  "employee_id": 1,
  "attendance_date": "2026-01-19",
  "sign_in_time": "08:30:00",
  "lunch_start_time": "12:00:00",
  "lunch_end_time": "13:00:00",
  "sign_out_time": "17:30:00",
  "sign_in_method": "QR Code",
  "lunch_out_method": "QR Code",
  "lunch_in_method": "QR Code",
  "sign_out_method": "QR Code",
  "status": "present",
  "notes": "Regular work day",
  "device_time": "2026-01-19 08:30:00"
}
```

**Success Response:**
```json
{
  "status": "success",
  "message": "Attendance synced successfully"
}
```

**Already Synced Response:**
```json
{
  "status": "success",
  "message": "Already synced"
}
```

**Error Response:**
```json
{
  "status": "error",
  "message": "Validation or server error"
}
```

---

## Offline Data Management

### Local Storage Structure

```javascript
// AsyncStorage Keys
STORAGE_KEYS = {
  EMPLOYEES: '@employees_cache',
  PENDING_ATTENDANCE: '@pending_attendance',
  SYNCED_ATTENDANCE: '@synced_attendance',
  LAST_SYNC: '@last_sync_time',
  USER_CREDENTIALS: '@user_credentials',
  APP_SETTINGS: '@app_settings'
}
```

### Pending Attendance Record Format
```json
{
  "local_uuid": "device-12345-record-67890",
  "employee_id": 1,
  "employee_name": "John Doe",
  "attendance_date": "2026-01-19",
  "sign_in_time": "08:30:00",
  "lunch_start_time": "12:00:00",
  "lunch_end_time": "13:00:00",
  "sign_out_time": null,
  "sign_in_method": "QR Code",
  "lunch_out_method": "QR Code",
  "lunch_in_method": "QR Code",
  "sign_out_method": null,
  "status": "present",
  "notes": "",
  "device_time": "2026-01-19 08:30:00",
  "sync_status": "pending",
  "created_at": "2026-01-19T08:30:00.000Z",
  "retry_count": 0
}
```

---

## App Screens/Components

### 1. Splash Screen
- App logo
- Loading indicator
- Check for cached data
- Initialize app state

### 2. Login Screen
- Username/password input
- Remember me checkbox
- Login button
- Error messages
- Offline indicator

### 3. Home/Dashboard Screen
- Welcome message with user name
- Statistics cards:
  - Total Employees
  - Present Today
  - Pending Sync
  - Attendance Rate
- Quick action buttons:
  - Scan QR Code
  - Sign In/Out
  - View Employees
  - View History
- Network status banner
- Last sync time display

### 4. QR Scanner Screen
- Camera viewfinder
- QR code overlay
- Flash toggle
- Cancel button
- Scan result feedback
- Auto-close on success

### 5. Employees List Screen
- Search bar
- Filter options
- Employee cards:
  - Photo placeholder
  - Name
  - Employee Number
  - Department
  - Status badge
- Pull-to-refresh
- Tap to view details

### 6. Employee Detail Screen
- Employee photo
- Full information display
- QR code display
- Quick action buttons:
  - Sign In
  - Sign Out
  - Lunch Start
  - Lunch End
- Attendance history for this employee

### 7. Attendance Entry Screen
- Manual attendance recording
- Employee selector
- Action type selector:
  - Sign In
  - Lunch Start
  - Lunch End
  - Sign Out
- Method selector:
  - QR Code
  - Facial Recognition
  - Manual
- Notes field
- Submit button
- Offline indicator

### 8. Attendance History Screen
- Date range selector
- List of attendance records
- Color-coded by status:
  - Green: Synced
  - Yellow: Pending
  - Red: Failed
- Tap to view details
- Swipe to retry sync
- Pull-to-refresh

### 9. Sync Queue Screen
- Pending records count
- List of pending records
- Individual record details
- Retry button for each
- Retry all button
- Clear synced records
- Force sync button

### 10. Settings Screen
- User profile
- Server URL configuration
- Sync settings:
  - Auto-sync toggle
  - Sync frequency
  - WiFi-only sync
- Cache management:
  - Clear cache button
  - Cache size display
- About section
- Logout button

---

## Key Implementation Details

### 1. Unique ID Generation (local_uuid)
```javascript
// Generate unique local_uuid for each attendance record
const generateLocalUUID = () => {
  const deviceId = DeviceInfo.getUniqueId(); // or generate a persistent device ID
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(7);
  return `${deviceId}-${timestamp}-${random}`;
};
```

### 2. Network Detection
```javascript
import NetInfo from '@react-native-community/netinfo';

// Subscribe to network state
NetInfo.addEventListener(state => {
  console.log('Connection type:', state.type);
  console.log('Is connected?', state.isConnected);

  if (state.isConnected) {
    // Trigger sync
    syncPendingAttendance();
  }
});
```

### 3. Sync Logic
```javascript
const syncPendingAttendance = async () => {
  // Get pending records
  const pendingRecords = await AsyncStorage.getItem(STORAGE_KEYS.PENDING_ATTENDANCE);
  const records = JSON.parse(pendingRecords || '[]');

  // Sync each record
  for (const record of records) {
    try {
      const response = await axios.post('/api/attendance/sync', record);

      if (response.data.status === 'success') {
        // Remove from pending queue
        await removePendingRecord(record.local_uuid);

        // Add to synced records
        await addSyncedRecord(record);
      }
    } catch (error) {
      // Increment retry count
      await incrementRetryCount(record.local_uuid);
      console.error('Sync failed:', error);
    }
  }

  // Update last sync time
  await AsyncStorage.setItem(STORAGE_KEYS.LAST_SYNC, new Date().toISOString());
};
```

### 4. Offline Storage
```javascript
// Save pending attendance
const savePendingAttendance = async (attendanceData) => {
  try {
    // Get existing pending records
    const pending = await AsyncStorage.getItem(STORAGE_KEYS.PENDING_ATTENDANCE);
    const records = JSON.parse(pending || '[]');

    // Add new record
    records.push({
      ...attendanceData,
      local_uuid: generateLocalUUID(),
      sync_status: 'pending',
      created_at: new Date().toISOString(),
      retry_count: 0
    });

    // Save back to storage
    await AsyncStorage.setItem(
      STORAGE_KEYS.PENDING_ATTENDANCE,
      JSON.stringify(records)
    );

    return true;
  } catch (error) {
    console.error('Failed to save pending attendance:', error);
    return false;
  }
};
```

### 5. QR Code Scanning
```javascript
import { RNCamera } from 'react-native-camera';

const QRScannerScreen = () => {
  const onBarCodeRead = async (event) => {
    const qrCode = event.data;

    // Fetch employee details
    const employee = await fetchEmployeeByQR(qrCode);

    if (employee) {
      // Determine action based on current status
      const action = determineAction(employee);

      // Record attendance
      await recordAttendance(employee, action, 'QR Code');

      // Show success feedback
      showSuccessMessage(`${action} recorded for ${employee.full_name}`);
    }
  };

  return (
    <RNCamera
      onBarCodeRead={onBarCodeRead}
      barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
    />
  );
};
```

---

## UI/UX Guidelines

### Design Principles
1. **Offline-First:** Design assumes offline by default
2. **Visual Feedback:** Clear indicators for network status, sync status
3. **Error Handling:** Graceful error messages, retry options
4. **Speed:** Fast response times, instant UI updates
5. **Simplicity:** Easy-to-use interface for non-technical users

### Color Scheme
- **Primary:** #667eea (Purple-blue)
- **Success:** #10b981 (Green)
- **Warning:** #f59e0b (Orange)
- **Danger:** #ef4444 (Red)
- **Neutral:** #6b7280 (Gray)

### Status Indicators
- **Online:** Green badge "Online"
- **Offline:** Orange badge "Offline"
- **Syncing:** Blue spinner "Syncing..."
- **Synced:** Green checkmark "Synced"
- **Pending:** Yellow clock "Pending"
- **Failed:** Red X "Failed"

---

## Error Handling

### Network Errors
```javascript
// Retry logic with exponential backoff
const syncWithRetry = async (record, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await axios.post('/api/attendance/sync', record);
      return response.data;
    } catch (error) {
      if (i === maxRetries - 1) throw error;

      // Wait before retry (exponential backoff)
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};
```

### Validation Errors
- Show clear error messages
- Highlight invalid fields
- Prevent form submission until valid
- Provide helpful hints

### Sync Conflicts
- Handle "Already synced" gracefully
- Remove from pending queue
- Update UI immediately
- Log for debugging

---

## Testing Requirements

### Unit Tests
- Storage functions
- UUID generation
- Date/time formatting
- Validation logic

### Integration Tests
- API calls
- Sync functionality
- Offline/online transitions
- Error handling

### E2E Tests
- Complete attendance flow
- QR scanning
- Offline recording
- Sync process

---

## Security Considerations

1. **Secure Storage:**
   - Use react-native-keychain for sensitive data
   - Encrypt local database

2. **API Security:**
   - Store API URL securely
   - Validate all inputs
   - Sanitize QR code data

3. **Data Privacy:**
   - Don't store passwords in plain text
   - Clear cache on logout
   - Respect app permissions

---

## Performance Optimization

1. **Lazy Loading:**
   - Load employee data in chunks
   - Paginate long lists

2. **Caching:**
   - Cache employee photos
   - Cache API responses
   - Clear old cache regularly

3. **Efficient Rendering:**
   - Use FlatList for long lists
   - Implement shouldComponentUpdate
   - Optimize re-renders

---

## Deliverables

Please provide:

1. **Complete Source Code:**
   - All screens and components
   - Navigation setup
   - State management
   - API integration
   - Offline sync logic

2. **Configuration Files:**
   - package.json with all dependencies
   - app.json or app.config.js
   - Environment variables setup

3. **Documentation:**
   - Setup instructions
   - How to run the app
   - How to build for production
   - API configuration guide

4. **Code Comments:**
   - Explain complex logic
   - Document all functions
   - Include usage examples

---

## File Structure

```
attendance-app/
├── src/
│   ├── components/
│   │   ├── AttendanceCard.js
│   │   ├── EmployeeCard.js
│   │   ├── SyncStatusBadge.js
│   │   ├── NetworkIndicator.js
│   │   └── StatCard.js
│   ├── screens/
│   │   ├── SplashScreen.js
│   │   ├── LoginScreen.js
│   │   ├── HomeScreen.js
│   │   ├── QRScannerScreen.js
│   │   ├── EmployeesListScreen.js
│   │   ├── EmployeeDetailScreen.js
│   │   ├── AttendanceEntryScreen.js
│   │   ├── AttendanceHistoryScreen.js
│   │   ├── SyncQueueScreen.js
│   │   └── SettingsScreen.js
│   ├── navigation/
│   │   ├── AppNavigator.js
│   │   └── AuthNavigator.js
│   ├── services/
│   │   ├── api.js
│   │   ├── storage.js
│   │   ├── sync.js
│   │   └── auth.js
│   ├── store/
│   │   ├── slices/
│   │   │   ├── employeesSlice.js
│   │   │   ├── attendanceSlice.js
│   │   │   ├── syncSlice.js
│   │   │   └── authSlice.js
│   │   └── store.js
│   ├── utils/
│   │   ├── uuid.js
│   │   ├── datetime.js
│   │   ├── validation.js
│   │   └── constants.js
│   └── App.js
├── assets/
│   ├── images/
│   └── icons/
├── android/
├── ios/
├── package.json
├── app.json
└── README.md
```

---

## Additional Notes

1. **Offline Priority:** The app MUST work fully offline. Online is a bonus.
2. **Data Integrity:** Never lose attendance records, even if app crashes
3. **User Experience:** Fast, intuitive, minimal clicks to record attendance
4. **Battery Efficient:** Optimize for long-running shifts
5. **Error Recovery:** Gracefully handle all error scenarios

---

## Example User Flow

**Scenario: Employee arrives at work (Offline)**

1. Security guard opens app
2. App shows "Offline Mode" indicator
3. Guard scans employee's QR code
4. App shows employee details instantly (from cache)
5. App records sign-in with timestamp
6. Shows success message: "Sign-in recorded (Pending Sync)"
7. Record saved locally with unique local_uuid
8. When WiFi connects:
   - App auto-detects connection
   - Shows "Syncing..." indicator
   - Uploads pending record to server
   - Receives "Attendance synced successfully"
   - Updates UI to show "Synced" status
   - Removes from pending queue

---

## Questions to Consider

Before starting, clarify:
1. Should the app support multiple locations/offices?
2. Is facial recognition required in v1 or can it be v2?
3. What's the maximum expected offline period? (1 day? 1 week?)
4. Should photos be synced or just attendance data?
5. Any specific devices to target? (Android only? iOS? Both?)

---

**Start by setting up the project structure, implementing offline storage, and then build the attendance recording flow. Focus on making offline mode rock-solid before adding online features.**

**Good luck! 🚀**
