File size: 6,149 Bytes
d464e87
8f2c1e9
d464e87
 
 
 
 
 
 
 
82fcb44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
---
title: Cuatro Labs Tracker
emoji: 🏭
colorFrom: yellow
colorTo: green
sdk: docker
pinned: false
short_description: Supply Chain Management - Merchant & Employee Management
---

# Tracker Microservice

Employee tracking and attendance management microservice for the Cuatro Labs platform.

## Features

### Attendance Management
- Employee check-in with GPS coordinates
- Location tracking consent validation
- Geofence detection support
- Duplicate check-in prevention
- Daily attendance records

## Architecture

### Technology Stack
- **Framework**: FastAPI 0.104.1
- **Database**: 
  - MongoDB (employee data, location settings)
  - PostgreSQL (attendance records)
- **Authentication**: JWT-based
- **Server**: Uvicorn with async support

### Project Structure
```
app/
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ config.py           # Configuration settings
β”‚   β”œβ”€β”€ logging.py          # Logging setup
β”‚   └── database.py         # SQLAlchemy base
β”œβ”€β”€ dependencies/
β”‚   └── auth.py             # JWT authentication
β”œβ”€β”€ tracker/
β”‚   └── attendance/
β”‚       β”œβ”€β”€ models.py       # SQLAlchemy models
β”‚       β”œβ”€β”€ schemas.py      # Pydantic schemas
β”‚       β”œβ”€β”€ service.py      # Business logic
β”‚       β”œβ”€β”€ router.py       # API endpoints
β”‚       └── constants.py    # Constants
β”œβ”€β”€ main.py                 # Application entry point
β”œβ”€β”€ nosql.py                # MongoDB connection
└── postgres.py             # PostgreSQL connection pool
```

## API Endpoints

### Attendance Endpoints

#### Check-In
**POST** `/api/v1/attendance/check-in`

Mark the start of an employee's working day.

**Request Body:**
```json
{
  "timestamp": 1708156800000,
  "latitude": 19.0760,
  "longitude": 72.8777,
  "location_id": "loc_mumbai_office_001"
}
```

**Response:**
```json
{
  "success": true,
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "message": "Check-in successful"
}
```

**Rules:**
- Can check-in only once per day
- Location coordinates are mandatory
- GPS tracking must be enabled (checked from MongoDB)
- Optional location_id if inside a geofence

**Edge Cases:**
- Duplicate check-in β†’ 400 error
- GPS disabled β†’ 400 error

## Database Schema

### PostgreSQL - trans.scm_attendance

```sql
CREATE TABLE trans.scm_attendance (
    id UUID PRIMARY KEY,
    merchant_id UUID NOT NULL,
    employee_id UUID NOT NULL,
    work_date DATE NOT NULL,
    check_in_time BIGINT,
    check_in_lat DOUBLE PRECISION,
    check_in_lon DOUBLE PRECISION,
    check_in_geofence_id UUID,
    check_out_time BIGINT,
    check_out_lat DOUBLE PRECISION,
    check_out_lon DOUBLE PRECISION,
    total_minutes INTEGER,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now(),
    UNIQUE (employee_id, work_date)
);

CREATE INDEX idx_scm_attendance_work_date 
ON trans.scm_attendance (employee_id, work_date);

CREATE INDEX idx_scm_attendance_merchant 
ON trans.scm_attendance (merchant_id, work_date);
```

### MongoDB - scm_employees

Location tracking consent is checked from:
```
scm_employees.location_settings.location_tracking_consent
```

## Environment Configuration

Copy `.env.example` to `.env` and configure:

```bash
# Application
APP_NAME=Tracker Microservice
APP_VERSION=1.0.0
DEBUG=false
LOG_LEVEL=INFO
PORT=8003

# MongoDB
MONGODB_URI=mongodb+srv://username:password@cluster0.2shrc.mongodb.net/?retryWrites=true&w=majority
MONGODB_DB_NAME=cuatrolabs

# PostgreSQL
DB_HOST=localhost
DB_PORT=5432
DB_NAME=cuatrolabs
DB_USER=postgres
DB_PASSWORD=your-password
DATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/cuatrolabs

# JWT
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
TOKEN_EXPIRATION_HOURS=8
```

## Getting Started

### Prerequisites
- Python 3.11+
- MongoDB (Atlas or local)
- PostgreSQL

### Local Development

1. Create and activate virtual environment:
```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Configure environment:
```bash
cp .env.example .env
# Edit .env with your configuration
```

4. Run the service:
```bash
uvicorn app.main:app --host 0.0.0.0 --port 8003 --reload
```

5. Access API documentation:
- Swagger UI: http://localhost:8003/docs
- ReDoc: http://localhost:8003/redoc

### Docker Deployment

```bash
# Build the image
docker build -t tracker-microservice .

# Run the container
docker run -p 8003:8003 --env-file .env tracker-microservice
```

## Testing

### Manual Testing with curl

```bash
# Health check
curl http://localhost:8003/health

# Check-in (requires JWT token)
curl -X POST http://localhost:8003/api/v1/attendance/check-in \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "timestamp": 1708156800000,
    "latitude": 19.0760,
    "longitude": 72.8777,
    "location_id": "loc_mumbai_office_001"
  }'
```

## Error Handling

The service provides structured error responses:

**400 Bad Request** - Business logic errors
```json
{
  "success": false,
  "error": "Already checked in today",
  "detail": "You have already checked in for today"
}
```

**401 Unauthorized** - Invalid or missing JWT token
```json
{
  "success": false,
  "error": "Unauthorized",
  "detail": "Invalid or expired token"
}
```

**422 Validation Error** - Invalid request data
```json
{
  "success": false,
  "error": "Validation Error",
  "errors": [
    {
      "field": "latitude",
      "message": "Latitude must be between -90 and 90",
      "type": "value_error"
    }
  ]
}
```

**500 Internal Server Error** - Unexpected errors
```json
{
  "success": false,
  "error": "Internal Server Error",
  "detail": "An unexpected error occurred"
}
```

## Logging

The service uses structured JSON logging with the following levels:
- DEBUG: Detailed diagnostic information
- INFO: General informational messages
- WARNING: Warning messages for recoverable issues
- ERROR: Error messages for failures
- CRITICAL: Critical errors requiring immediate attention

## License

Part of the Cuatro Labs platform.